开发者

how to restrain bash from removing blanks when processing file

开发者 https://www.devze.com 2023-02-10 18:55 出处:网络
A simple yet annoying thing: Using a script like this: while read x; do echo \"$x\" done<file on a file containing whitespace:

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?


read is stripping the whitespace. Wipe $IFS first.

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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消