Thursday, May 2, 2024
4
rated 0 times [  4] [ 0]  / answers: 1 / hits: 816  / 3 Years ago, sat, september 11, 2021, 8:01:18

In my file 'foo' there is a first line: 'a b', and the second line: 'c d':


$ cat foo
a b
c d

I want to print in terminal in loop these two lines: one after another:


$ for i in $(cat foo); do echo $i; done

But in the output 'echo' command breaks the order, so instead of having:


a b
c d

I actually have:


a
b
c
d

More From » command-line

 Answers
0

for i in $(cat foo) does not loop lines but words (or fields) split by your field separator $IFS. It default to
(space, newline, tab).


If you change your field separator to newline only, you can use your command as is (Disclaimer: please read below!):


IFS=$'
'
for i in $(cat foo); do echo $i; done

You might want to make a backup of IFS to restore it later:


OLD_IFS="$IFS"
.
.
.
IFS="$OLD_IFS"

Output:


a b
c d



However, this is considered bad practice.



  • Bit Better: while IFS= read -r line; do ... done < file

  • Much better: Use a dedicated tool for your task such as grep, sed or awk.


Please read Why is using a shell loop to process text considered bad practice?.


[#951] Sunday, September 12, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
umplegitimat

Total Points: 137
Total Questions: 126
Total Answers: 118

Location: Saint Pierre and Miquelon
Member since Sat, Aug 21, 2021
3 Years ago
umplegitimat questions
Mon, Aug 23, 21, 20:57, 3 Years ago
Fri, Jun 18, 21, 20:48, 3 Years ago
Sun, Dec 4, 22, 00:11, 1 Year ago
;