2 while read loops?

2020-02-13 04:08发布

问题:

So the object of the script I'm making is to compare files from two while read lists that have file path names in them...

while read compareFile <&3; do     
 if [[ ! $server =~ [^[:space:]] ]] ; then  #empty line exception
  continue
 fi   
    echo "Comparing file - $compareFile"
 if diff "$compareFile" _(other file from loop?_) >/dev/null ; then
    echo Same
 else
     echo Different
 fi   
 done 3</infanass/dev/admin/filestoCompare.txt

I need to be able to compare files from two different lists at the same time through two while read loops... Is this even possible?

回答1:

I think I would restructure that along these lines:

while true
do
   read -u3 line1 || break
   read -u4 line2 || break

   # do whatever...
done 3< file1 4< file2

That uses a single loop, and will exit that loop when end of file is reached on either input file. The logic would be a little more complicated if you want to read both files entirely, even if one ends early...



回答2:

Not really understand what you want achieve, but the next:

while read -r file1 file2
do
    echo diff "$file1" "$file2"
done < <(paste <(grep . list1.txt) <(grep . list2.txt))

where the list1.txt contains:

file1.txt
file2.txt

file3.txt

file4.txt
file5.txt

and the list2.txt contains:

another1.txt

another2.txt
another3.txt
another4.txt

another5.txt

produces the next output:

diff file1.txt another1.txt
diff file2.txt another2.txt
diff file3.txt another3.txt
diff file4.txt another4.txt
diff file5.txt another5.txt

Remove the echo before the diff if you satisfied.



回答3:

if I understand you correctly...yes. Here's an example of looping through two files in lock-step

exec 3<filelist1.txt
exec 4<filelist2.txt
while read -r file1 <&3 && read -r file2 <&4; do echo ${file1}","${file2}; done
exec 3>&- 4>&-


回答4:

while read newfile <&3; do   
 if [[ ! $newfile =~ [^[:space:]] ]] ; then  #empty line exception
    continue
 fi   
 #
 while read oldfile <&3; do   
 if [[ ! $oldfile =~ [^[:space:]] ]] ; then  #empty line exception
    continue
 fi   
    echo Comparing "$newfile" with "$oldfile"
    #
    if diff "$newfile" "$oldfile" >/dev/null ; then
      echo The files compared are the same. No changes were made.
    else
        echo The files compared are different.
        #
    fi    
  done 3</home/u0146121/test/oldfiles.txt
 done 3</home/u0146121/test/newfiles.txt