Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

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?

like image 443
mlebel Avatar asked Mar 15 '13 21:03

mlebel


People also ask

How read file line by line in shell script and store each line in a variable?

We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \n and print the contents of the line variable.

How read a file line by line in Linux shell script?

Syntax: Read file line by line on a Bash Unix & Linux shell file. The -r option passed to read command prevents backslash escapes from being interpreted. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed. while IFS= read -r line; do COMMAND_on $line; done < input.


1 Answers

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 
like image 72
chepner Avatar answered Sep 18 '22 06:09

chepner