0

Hello everyone I'm very new to the game so my question is probably rather simple but I'm stuck at this for a long time. I want to process two files from two list of files simultaneously line by line.

I'm trying currently:

 read file1 && read file2; 
    do 
    echo "$file1 and $file2"
    done 

The echo is of course just a spaceholder for the rest of the script but i didn't manage to get any variables out of the read operation.

Biffen
  • 6,249
  • 6
  • 28
  • 36
Deebob
  • 11
  • 1
  • 2

2 Answers2

11

You need two separate file descriptors to read from two files at once. One of them can be standard input.

while IFS= read -r line1 && IFS= read -r line2 <&3; do
  echo "File 1: $line1"
  echo "File 2: $line2"
done < file1 3< file2
chepner
  • 497,756
  • 71
  • 530
  • 681
-1
LINECOUNTER=1
while true; do
    FILE1INPUT="$(sed -n "${LINECOUNTER}p" file1.txt)"
    FILE2INPUT="$(sed -n "${LINECOUNTER}p" file2.txt)"
    echo "$FILE1INPUT and $FILE1INPUT"
    let LINECOUNTER=LINECOUNTER+1
done
  • The LINECOUNTER variable is just to memorize which line to output next.
  • Then you assign the output of the sed command $(sed ...) to the variable FILE1INPUT. This sed command just reads one line, specified by LINECOUNTER from file1.txt. Same with file2.txt
  • Then LINECOUNTER is incremented by one, so that the next time sed is executed the next line is returned.

Of course one needs an appropriate condition for the while loop to end.

Paul
  • 293
  • 2
  • 12