Think before you speak, read before you think.

将数据文件的指定域读取到shell脚本中

这个例子说明了怎样在 shell 脚本中从数据文件读取特定的域(field)并进行操作。例如,假设文件 employees.txt 的格式是{employee-name}:{employee-id}:{department-name},以冒号进行划分,如下所示。

$ cat employees.txt

Emma Thomas:100:Marketing
Alex Jason:200:Sales
Madison Randy:300:Product Development
Sanjay Gupta:400:Support
Nisha Singh:500:Sales

下面的 shell 脚本说明了如何从这个 employee.txt 文件中读取特定的域(field)。

 $ vi read-employees.sh
#!/bin/bash
IFS=:
echo "Employee Names:"
echo "---------------"
while read name empid dept
do 
   echo "$name is part of $dept department"
done < ~/employees.txt

赋予脚本可执行权限后执行该脚本

 $ chmod u+x read-employees.sh 
 $ ./read-employees.sh 

Employee Names:
—————
Emma Thomas is part of Marketing department
Alex Jason is part of Sales department
Madison Randy is part of Product Development department
Sanjay Gupta is part of Support department
Nisha Singh is part of Sales department

来自:http://www.linuxnote.org/the-data-file-to-the-specified-domain-to-read-shell-scripts.html


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *