Search code examples
linuxshell

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?


Solution

  • 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