Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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

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 paste to put these files together, and then in a while loop use cut to separate them like this:

paste x-file y-file char-file | while -r line; do
    Y=$(echo "$line" | cut -d  -f1)
    X=$(echo "$line" | cut -d  -f2)
    CHAR=$(echo "$line" | cut -d  -f3)
done

but the problem with this is that it's really slow (calling cut again and again).

How should I do this to have in each loop proper values in $Y, $X and $CHAR while speeding things up?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...