How to read a file:
First step: Pass the contents of the file to the while by pipe (|) or redirect (<)
The second step is to call read in the while and read the contents of the file one line at a time and pay the value to the variable following read. The contents of the current row are saved in the variable.
For example, read file/sites/linuxpig.com.txt
1) How to pipe:
cat /sites/linuxpig.com.txt |while read LINE do echo $LINE done当然也可以将cat /sites/linuxpig.com.txt 写成一些复杂一些的,比如:示例1:find -type f -name "*.txt" -exec cat |while read LINE do echo $LINE done可以将当前目录所有以 .txt 结尾的文件读出示例2:grep -r "linuxpig.com" ./ | awk -F":" ‘{print $1}‘ | cat |while read LINE do echo $LINE done可以将含有 "linuxpig.com" 字符串的所有文件打开并读取。。示例没有实际测试,如果使用请先测试。。。。。:-)
2) How to redirect:
2.1 using redirects <
while read LINE do echo $LINE done < /sites/linuxpig.com.txt
2.2 Using file descriptors (0~9) and redirects <
exec 3<&0 #先将文件描述符0复制到文件描述符3,也就是给文件描述符0做个备份 exec 0</sites/linuxpig.com.txt #读文件到文件描述符0 while read LINE # 此变量是读来自stdin(即描述符0)的数据 do echo $LINE done exec 0<&3 #将文件描述符3复制给文件描述符0(恢复0从键盘读入)
Done after a while loop in the shell followed by a redirect <