In bash, "for; do echo; done" separates lines in spaces

In bash on Mac OSX, I have a file (test case) containing 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 to make the echo give me "x xx xxx"?

+7
source share
3 answers

By default, the Bash for loop breaks into all spaces. You can override this by setting the IFS variable:

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

Either set IFS as suggested, or use while :

 while read theline; do echo "$theline"; done <thefile 
+3
source
 IFS="\n" for i in `cat r.txt`; do echo "$i"; done unset IFS 
-one
source

All Articles