for i in $(cat foo)
does not loop lines but words (or fields) split by your field separator $IFS
. It default to \n\t
(space, newline, tab).
If you change your field separator to newline only, you can use your command as is (Disclaimer: please read below!):
IFS=$'\n'
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?.
for i in $(cat foo)
does not loop lines but words split by your field separator (IFS
). – pLumo Dec 08 '21 at 12:18sed
or so., – pLumo Dec 08 '21 at 12:34