Several common methods for shell to read files by line
1. By redirecting the + read command
While read linedo # Operation on each line of string shell_commandsdone < File.txt
two。 Redefine through cat + IFS
IFS_old=$IFSIFS=$'\ n'for line in $(cat File.txt) do shell_commandsdoneIFS=$IFS_old
3. Pipe + read command (often seen, but not easy to use. )
Cat File.txt | read linedo shell_commandsdone
Note: this approach has a very obvious flaw. Variables defined by shell_command will "fail" at the end of the loop!
For example:
The file1.txt is as follows:
Abcd
The shell code for method 1:
# number of lines line_count=0# file contents file_content= "# start reading while read linedo echo" I read: "echo ${line} line_count=$ (expr $line_count + 1) echo" this is the ${line_count} line "file_content=" $file_content $line "done"