a.txt文件末尾有两个空行
[yaxin@oishi tmp]$ cat -n a.txt
1 jhasdfj
2
3 sdfjalskdf
4
5
我的脚本是:
[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
打开调试
[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
cat 命令窃取了文件末尾的空行。如何解决这个问题。
最佳答案
cat
命令不会窃取任何东西。这是命令替换。 man bash
说:
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
如果要将命令的输出存储到变量中,可以在命令后添加 && echo .
,存储输出并删除最后的 .
。
此外,要计算文件中的行数,规范的方法是运行 wc -l
:
wc -l < a.txt
关于linux - 当我在 shell 脚本中使用 cat 命令时,如何在文件末尾保留空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18226491/