这个例子说明了怎样在Linux下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
【编辑推荐】