How to read multiple files at the same time in the shell

  
                  

1. Reading a single file

Under shell scripts, you can read files in rows in a variety of ways, as follows:
for line in `cat ${input_filename}`do echo $ Linedone while read linedo echo $linedone < ${input_filename}

The second way is to redirect the file to standard input

2. Multiple file reading methods

How to achieve simultaneous reading of multiple files? We can continue to use the file redirection function in bash to redirect the file to a specific file descriptor with the following syntax:
n<filen>filen>>filen<>file

where n represents Open the file descriptor of the file file, similar to fd in other programming languages. If n is not specified, its default behavior is as follows:
<file #same as 0<file>file #same as 1>file<> File #same as 0<>file

We can open the file to be redirected by the exec command:
exec 7<file1exec 8<file2

Then we can read the corresponding file by the read command. Content:
read data <&7 #Use conformance is to distinguish 7 is the file descriptor, not the file name read data <&8

close the file
exec 7</dev/nullexec 8</dev/null

The sample file 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<$fil E1 exec 8<$file2 while [[ $eof1 -eq 0

Copyright © Windows knowledge All Rights Reserved