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?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With