Read from two files line by line and process them simultaneously

前端 未结 2 817
面向向阳花
面向向阳花 2020-12-12 07:33

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

相关标签:
2条回答
  • 2020-12-12 08:16
    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.

    0 讨论(0)
  • 2020-12-12 08:31

    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
    
    0 讨论(0)
提交回复
热议问题