Transferred from: http://hi.baidu.com/%CE%D2%D2%AA_%D1%A7_%CF%B0/blog/item/b3b5e723bb2ed1265243c1e4.html
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
Of course, Cat/sites/linuxpig.com.txt can also be written in some complex, such as:
Example 1:
Find-type f-name "*.txt"-exec cat |while Read line
Do
Echo $LINE
Done
All files ending in. txt can be read in the current directory
Example 2:
Grep-r "linuxpig.com"./| Awk-f ":" ' {print $} ' | Cat |while Read Line
Do
Echo $LINE
Done
You can open and read all files that contain the string "linuxpig.com".
Examples are not actually tested, if used please test first ..... :-)
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, which is to make a backup of the file descriptor 0
EXEC 0</sites/linuxpig.com.txt #读文件到文件描述符0
While reading line # This variable is read data from stdin (that is, descriptor 0)
Do
Echo $LINE
Done
EXEC 0<&3 #将文件描述符3复制给文件描述符0 (recovery 0 read from keyboard)
Done after a while loop in the shell followed by a redirect <