atheaos
atheaos

Reputation: 729

in bash, "for;do echo;done" splits lines at spaces

In bash on Mac OSX, I have a file (test case) that contains the lines

x xx xxx
xxx xx x

But when I execute the command

for i in `cat r.txt`; do echo "$i"; done

the result is not

x xx xxx
xxx xx x

as I want but rather

x
xx
xxx
xxx
xx
x

How do I make echo give me 'x xx xxx'?

Upvotes: 15

Views: 13745

Answers (3)

fge
fge

Reputation: 121720

Either setting IFS as suggested or use while:

while read theline; do echo "$theline"; done <thefile

Upvotes: 3

Arenielle
Arenielle

Reputation: 2857

IFS="\n"
for i in `cat r.txt`; do echo "$i"; done
unset IFS

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

By default, a Bash for loop splits on all whitespace. You can override that by setting the IFS variable:

IFS=$'\n'
for i in `cat r.txt`; do echo "$i"; done
unset IFS

Upvotes: 36

Related Questions