Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep blank lines in the end of a file when I user cat command in shell script

Tags:

linux

shell

the file a.txt has two blank lines at the end

[yaxin@oishi tmp]$ cat -n a.txt 
     1  jhasdfj
     2  
     3  sdfjalskdf
     4  
     5  

and my script is:

[yaxin@oishi tmp]$ cat t.sh 
#!/bin/sh
a=`cat a.txt`
a_length=`echo "$a" | awk 'END {print NR}'`
echo "$a"
echo $a_length


[yaxin@oishi tmp]$ sh t.sh 
jhasdfj

sdfjalskdf
3

open debug

[yaxin@oishi tmp]$ sh -x t.sh 
++ cat a.txt
+ a='jhasdfj

sdfjalskdf'
++ echo 'jhasdfj

sdfjalskdf'
++ awk 'END {print NR}'
+ a_length=3
+ echo 'jhasdfj

sdfjalskdf'
jhasdfj

sdfjalskdf
+ echo 3
3

the cat command steal the blank lines at the end of the file.How to solve this problem.

like image 863
yaxin Avatar asked Oct 04 '22 06:10

yaxin


1 Answers

The cat command does not steal anything. It is the command substitution that does. man bash says:

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted

If you want to store an output of a command to a variable, you might add && echo . after the command, store the output and remove the final ..

Also, to count the number of lines in a file, the cannonical way is to run wc -l:

wc -l < a.txt
like image 105
choroba Avatar answered Oct 07 '22 20:10

choroba