How to restrain bash from removing spaces while processing a file

A simple but annoying thing:
Using a script as follows:

while read x; do echo "$x" done<file 

in a file containing spaces:

  text 

will give me a way out without spaces:

 text 

The problem is that I need this space in front of the text (this is one tab mainly, but not always).
So the question is: how to get identical lines, like in the input file in a script?


Update: Good, so I changed my while read x to while IFS= read x .

echo "$x" gives the correct answer without removing the first tab , but , eval "echo $x" removes this tab.

What should I do then?

+6
bash
source share
3 answers

read removes spaces. Wipe $IFS .

 while IFS= read x do echo "$x" done < file 
+14
source share

All reading contents are placed in a variable named REPLY. If you use REPLY instead of "x", you don’t have to worry about splitting the read words and IFS and all that.

I ran into the same problem you are encountering while trying to strip spaces from the end of file names. REPLY came to the rescue:

 find . -name '* ' -depth -print | while read; do mv -v "${REPLY}" "`echo "${REPLY}" | sed -e 's/ *$//'`"; done 
+1
source share

I found a solution to the problem "eval" echo $ x "crosses this tab. This should fix this:

 eval "echo \"$x\"" 

I think this causes the inner (shielded) quotes to be evaluated using an echo, whereas I think both

 eval "echo $x" 

and

 eval echo "$x" 

call quotes to evaluate before the echo, which means that the line passed to echo does not have quotes, resulting in empty space being lost. So the full answer is:

 while IFS= read x do eval "echo \"$x\"" done < file 
+1
source share

All Articles