Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Bash to read line by line and keep space

Tags:

bash

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?

like image 220
paler Avatar asked Sep 06 '11 01:09

paler


People also ask

How do I read a text file line by line in bash?

Syntax: Read file line by line on a Bash Unix & Linux shell file. The -r option passed to read command prevents backslash escapes from being interpreted. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed. while IFS= read -r line; do COMMAND_on $line; done < input.

Does bash ignore whitespace?

Bash uses whitespace to determine where words begin and end. The first word is the command name and additional words become arguments to that command.


2 Answers

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 
like image 96
DigitalRoss Avatar answered Oct 02 '22 12:10

DigitalRoss


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 
like image 42
Joshua Davies Avatar answered Oct 02 '22 14:10

Joshua Davies