kasper
kasper

Reputation: 631

how to restrain bash from removing blanks when processing file

A simple yet annoying thing:
Using a script like this:

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

on a file containing whitespace:

    text

will give me an output without the whitespace:

text

The problem is i need this space before text (it's one tab mostly but not always).
So the question is: how to obtain identical lines as are in input file in such a script?


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

echo "$x" gives me correct answer without stripping first tab, but, eval "echo $x" strips this tab.

What should I do then?

Upvotes: 6

Views: 2377

Answers (3)

Ken
Ken

Reputation: 719

I found the solution to the problem 'eval "echo $x" strips this tab.' This should fix it:

eval "echo \"$x\""

I think this causes the inner (escaped) quotes will be evaluated with the echo, whereas I think that both

eval "echo $x"

and

eval echo "$x"

cause the quotes to be evaluated before the echo, which means that the string passed to echo has no quotes, causing the white space to be lost. So the complete answer is:

while IFS= read x
do
  eval "echo \"$x\""
done < file

Upvotes: 1

tom d
tom d

Reputation: 111

The entire contents of the read are put into a variable called REPLY. If you use REPLY instead of 'x', you won't have to worry about read's word splitting and IFS and all that.

I ran into the same trouble you are having when attempting to strip spaces off the end of filenames. REPLY came to the rescue:

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

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798516

read is stripping the whitespace. Wipe $IFS first.

while IFS= read x
do
  echo "$x"
done < file

Upvotes: 14

Related Questions