Use Bash to read line by line and keep space

Bash

Bash Problem Overview


When I use "cat test.file", it will show

1
 2
  3
   4

When I use the Bash file,

cat test.file |
while read data
do
    echo "$data"
done

It will show

1
2
3
4

How could I make the result just like the original test file?

Bash Solutions


Solution 1 - Bash

IFS=''
cat test.file |
while read data
do
    echo "$data"
done

I realize you might have simplified the example from something that really needed a pipeline, but before someone else says it:

IFS=''
while read data; do
    echo "$data"
done < test.file

Solution 2 - Bash

Actually, if you don't supply an argument to the "read" call, read will set a default variable called $REPLY which will preserve whitespace. So you can just do this:

$ cat test.file | while read; do echo "$REPLY"; done

Solution 3 - Bash

Just to complement DigitalRoss's response.

For that case that you want to alter the IFS just for this command, you can use parenthesis. If you do, the value of IFS will be changed only inside the subshell. Like this:

echo '  word1
  word2' |  ( IFS='' ; while read line ; do echo "$line" check ; done ; )

The output will be (keeping spaces):

  word1 check
  word2 check

Solution 4 - Bash

Maybe IFS is the key point as others said. You need to add only IFS= between while and read.

cat test.file | 
while IFS= read data 
 do echo "$data"
 done

and do not forget quotations of $data, else echo will trim the spaces.

But as Joshua Davies mentioned, you would prefer to use the predefined variable $REPLY.

Solution 5 - Bash

read data will split the data by IFS, which is typically " \t\n". This will preserve the blanks for you:

var=$(cat test.file)
echo "$var"

Solution 6 - Bash

Alternatively, use a good file parsing tool, like AWK:

awk '{
  # Do your stuff
  print 
}' file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpalerView Question on Stackoverflow
Solution 1 - BashDigitalRossView Answer on Stackoverflow
Solution 2 - BashJoshua DaviesView Answer on Stackoverflow
Solution 3 - BashdiogovkView Answer on Stackoverflow
Solution 4 - BashplhnView Answer on Stackoverflow
Solution 5 - BashMu QiaoView Answer on Stackoverflow
Solution 6 - Bashghostdog74View Answer on Stackoverflow