Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

echo

macos

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'?

like image 963
atheaos Avatar asked Jan 01 '12 18:01

atheaos


2 Answers

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
like image 136
Oliver Charlesworth Avatar answered Sep 22 '22 21:09

Oliver Charlesworth


Either setting IFS as suggested or use while:

while read theline; do echo "$theline"; done <thefile
like image 32
fge Avatar answered Sep 21 '22 21:09

fge