Bash string concatenation with variable interpolation

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

Why is there no newline character when I assign a string to a variable? How to save a newline character in space?

I am using bash.

+3
source share
2 answers

You must specify a variable to preserve newlines.

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

And catnot required in both cases:

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

Edit:

Bash usually extracts additional trailing lines from a file when it assigns its contents to a variable. You have to resort to some tricks to save them. Try the following:

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

IFS read null, .

+4
var=($(< file))
echo ${#var[@]}
0

Source: https://habr.com/ru/post/1758840/


All Articles