在 Shell 脚本中读文件内容

这个名字好长... 其实也没什么东西, 无非是重定向和read的组合拳. 不过嘛, 这一拳还是很给力的 :)

假设有这样一个文件:

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

还记得这个文件吗 ~

然后我们写一个脚本:

$ 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

好玩吗?

解释一下:

IFS表示的是分隔符, 因为我们给的文件里面就是用这个冒号来分隔的. 然后重定向将txt文件里面的内容都给了read, 每次读一行, 一行读三个. 然后echo再把read读到的内容输出出来.

事情就是这么个事情,情况就是这么个情况.

results matching ""

    No results matching ""