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?
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