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
521 views
in Technique[技术] by (71.8m points)

bash - How do I pipe a file line by line into multiple read variables?

I have a file that contains information in two columns:

box1 a1
box2 a2

I'm trying to read this file line by line into read and have each line items be put into a variable.

On the first pass, $a would contain box1 and $b would contain a1.

On the second pass, $a would contain box2 and $b would contain a2, etc.

An example of the code that I am using to try to achieve is this:

for i in text.txt; do
    while read line; do
        echo $line | read a b;
    done < text.txt;
    echo $a $b;
done

This gives me the following results:

box1 a1 box2 a2

When I expected the following results:

box1 a1
box2 a1

How can I fix this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Piping into a read command causes the variables to be set in a subshell, which makes them inaccessible (indeed, they are gone) to the rest of your code. In this case, though, you don't even need the for loop or the second read command:

while read -r a b; do
    echo "$a" "$b"
done < text.txt

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

...