1. Single File read
Under the shell script, you can read files by rows in a variety of ways, as follows:
For line in ' Cat ${input_filename} '
Todo
Echo $line
Done
While Read line
Todo
Echo $line
Done < ${input_filename}
The second way is to redirect files to standard input
2. Multiple file reading methods
How do you achieve simultaneous reading of multiple files?
We can continue to use the file redirection feature in bash to redirect files to a specific file descriptor with the following syntax:
N
N>file
N>>file
N<>file
The n here represents the file descriptor for opening file files, similar to the FD in other programming languages, and if n is not specified, the default behavior is as follows:
>file #same as 1>file
<>file #same as 0<>file
We can open the file you want to redirect by using the EXEC command:
EXEC 7
EXEC 8
We can then read the contents of the corresponding file through the Read command:
Read Data <&7 #使用符合是为了区分7是文件描述符, not filename
Read Data <&8
Close File
EXEC 7
EXEC 8
The sample code for multiple file reads is as follows:
Readfiles () {
Local fd1=7
Local fd2=8
Local file1=$1
Local file2=$2
Local count1=0
Local count2=0
Local eof1=0
Local eof2=0
Local data1
Local data2
# Open files.
EXEC 7< $file 1
EXEC 8< $file 2
while [[$eof 1-eq 0 | | $eof 2-eq 0]]
Todo
If read data1<& $FD 1; Then
Let count1++
printf "%s, line%d:%sn" $file 1 $count 1 "$data 1"
Else
Eof1=1
Fi
If read data2 <& $FD 2; Then
Let count2++
printf "%s, line%d:%sn" $file 2 $count 2 "$data 2"
Else
Eof2=1
Fi
Done
}
#read File1 and File2
Readfiles file1 file2