Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
951 views
in Technique[技术] by (71.8m points)

bash - Read from two files line by line and process them simultaneously

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...