I am parsing a file using grep and the output on screen contains newline, as here:
$ grep 'gene' sequence.gb
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"
I can assign this to a variable and print out still with the newlines:
$ gene=$(grep 'gene' sequence.gb)
echo "$gene"
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"
but this does not contain real newlines, since if I grep again for the lines containing '..' I get the whole lot:
$ echo "$gene" | grep '..'
gene 89..1483
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
/gene="non-structural protein"
gene complement(1987..2763)
/gene="nucleocapsid protein"
/gene="nucleocapsid protein"
We can see that this is a single string by not using the quotes:
$ echo $gene
gene 89..1483 /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" /gene="non-structural protein" gene complement(1987..2763) /gene="nucleocapsid protein" /gene="nucleocapsid protein"
So my question is, how can I maintain newline formatting or introducing it?
Thank you
gene
will have all whitespace collapsed into a single space; it does not indicate what the composition of that white space would have been..
in regexes, there is the semi-related issue that command substitution removes trailing newlines when returning the value. You can't see it here, sinceecho
adds one for you. But if your command produced empty lines at the end, they'd be lost. (thegrep
here won't do that, of course.)echo "$var" | od -c
(orxxd
orhd
etc) orecho "$var" | cat -n
(or-E
or-En
if GNU coreutils) orecho "$var" | awk '{print NR,$0}'
etc.