views:

119

answers:

2
$ cat isbndb.sample | wc -l
13
$ var=$(cat isbndb.sample); echo $var | wc -l
1

Why is the newline character missing when I assign the string to the variable? How can I keep the newline character from being converted into a space?

I am using bash.

+1  A: 

You have to quote the variable to preserve the newlines.

$ var=$(cat isbndb.sample); echo "$var" | wc -l

And cat is unnecessary in both cases:

$ wc -l < isbndb.sample
$ var=$(< isbndb.sample); echo "$var" | wc -l

Edit:

Bash normally strips extra trailing newlines from a file when it assigns its contents to a variable. You have to resort to some tricks to preserve them. Try this:

IFS='' read -d '' var < isbndb.sample; echo "$var" | wc -l

Setting IFS to null prevents the file from being split on the newlines and setting the delimiter for read to null makes it accept the file until the end of file.

Dennis Williamson
$var=$(cat isbndb.sample); echo "$var" | wc -l. the output is 12, missing one line, why? i using cat to read from file, because in my program it's actually the output of another cmd.
it seems my last empty line is omitted. how to fix this? thanks
@user408393: See my edit.
Dennis Williamson
A: 
var=($(< file))
echo ${#var[@]}
ghostdog74
sorry, it does not work.