1

I am trying to read in a file using read in bash 3.2, but read seems to be converting any instance of multiple whitespace into a single space.

For example, the code below has two tabs between "hello" and "there", and three spaces between "today" and "world":

while read -r LINE; do
    echo $LINE
done <<< "hello     there
today   world"

However, when run, it outputs with only a space in between each set of words:

hello there
today world

Instead, I'd like it to output the lines with whitespace preserved, e.g.:

hello       there
today   world

Is there any way to do this? If not with read, then with something else?

1 Answers1

7

Put quotes around your variable when you print it. It's being expanded then word split so echo is getting hello and there as separate arguments.

echo "$LINE"

or better

printf '%s\n' "$LINE"

will keep your whitespace

so it's not the read that's changing your whitespace, it's your not quoting the variable later

Eric Renouf
  • 18,431
  • 4
    To preserve any leading / trailing whitespace, it's also necessary to unset the field separator variable I think? i.e. while IFS= read -r LINE – steeldriver Aug 06 '17 at 00:36
  • @steeldriver You are right, read also eats whitespace. Alternatively, you can also do read -r and use the REPLY variable instead of LINE. – xhienne Aug 06 '17 at 00:54