How to read a line from each of several files in each iteration of a single loop?

前端 未结 2 1603
小蘑菇
小蘑菇 2020-12-21 16:46

I need to read from multiple file in one loop. I have one file with X coords, one file with Y coords and one file with chars on those coords.

For now I use pas

相关标签:
2条回答
  • 2020-12-21 17:04

    You can call read thrice, each from a different file descriptor.

    # Use && to stop reading once the shortest file is consumed
    while read -u 3 -r X &&
          read -u 4 -r Y &&
          read -u 5 -r CHAR; do
        ...
    done 3< X.txt 4< Y.txt 5< CHAR.txt 
    

    (-u is a bash extension, used for clarity. For POSIX compatibility, each call would look something like read -r X <&3.)

    0 讨论(0)
  • 2020-12-21 17:10

    I'm not sure how to do it without paste, but you can avoid cut assigning all variables in one read:

    while read -r X Y CHAR; do
        echo "X = $X; Y = $Y; CHAR = $CHAR";
    done < "$file"
    
    0 讨论(0)
提交回复
热议问题