tags:

views:

91

answers:

3

I have a text file test.txt with the following content:
text1
text2

And I want to assign the content of the file to a UNIX variable but when I do this:

testvar=$(cat test.txt)

echo $testvar the reult is:

text1 text2

instead of

text1
text2

Can someone suggest me a solution for this?

+1  A: 

This is due to IFS (Internal Field Separator) variable which contains newline.

$ cat xx1
1
2

$ A=`cat xx1`
$ echo $A
1 2

$ echo "|$IFS|"
|       
|

A workaround is to reset IFS to not contain the newline, temporarily:

$ IFSBAK=$IFS
$ IFS=" "
$ A=`cat xx1` # Can use $() as well
$ echo $A
1
2
$ IFS=$IFSBAK
DVK
+2  A: 

The assignment does not remove the newline characters, it's actually the echo doing this. You need simply put quotes around the string to maintain those newlines:

echo "$testvar"

This wil give the result you want. See the following transcript for a demo:

pax> cat num1.txt
line 1
line 2

pax> x=$(cat num1.txt)

pax> echo $x
line 1 line 2

pax> echo "$x"
line 1
line 2

pax> echo "$x" >num2.txt

pax> cat num2.txt
line 1
line 2

pax> diff num1.txt num2.txt

pax> _
paxdiablo
A: 

Bash -ge 4 has the mapfile builtin to read lines from the standard input into an array variable.

help mapfile 

mapfile < file.txt lines
printf "%s" "${lines[@]}"

mapfile -t < file.txt lines    # strip trailing newlines
printf "%s\n" "${lines[@]}" 

See also:

http://bash-hackers.org/wiki/doku.php/commands/builtin/mapfile

todd