rednectar
rednectar

Reputation: 176

How to stop read stripping spaces

I'm trying to parse a file, changing a line here and there. I have a simple loop like this:

while read line; do
  if *condition* then ; 
    echo *someChangedOutput* >> newfile
  else
    echo "$line" >> newfile
  fi
done < oldfile

My problem is that most of the lines in "oldfile" have leading spaces. When I read them into the variable line, the leading spaces get stripped off - and so are missing when I echo "$line" to "newfile"

For instance, if "oldfile" is:

line1
      line2
   line3

"newfile" gets created as

line1
line2
line3

How can I read a line from a file WITHOUT having the leading spaces stripped?

Upvotes: 2

Views: 353

Answers (2)

anubhava
anubhava

Reputation: 784898

You can use read like this with special variable REPLY:

while IFS= read -r; do
  if *condition* then
    echo *someChangedOutput*
  else
    printf '%s\n' "$REPLY"
  fi
done < oldfile >> newfile

Upvotes: 2

Adrian Fr&#252;hwirth
Adrian Fr&#252;hwirth

Reputation: 45526

See http://mywiki.wooledge.org/BashFAQ/001. You need to unset IFS to avoid stripping off leading and trailing whitespace, and you most probably also want to use -r:

while IFS= read -r line; do
    do_something_with "${line}"
done

Upvotes: 3

Related Questions