linux - 当我在 shell 脚本中使用 cat 命令时,如何在文件末尾保留空行

标签 linux shell

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/

相关文章:

linux - wget 使用环境变量

linux - Tex 发送另一个命令

c++ - QTimer timeout() 方法在代码重组后不再触发

linux - UNIX 命令中的隐式系统调用

php - 尝试在 PHP/Apache 中执行 exec ("unix2dos xxx"时出现问题

android - Adb Shell InputText 太长

linux - 我应该担心流程组中的哪些流程接收信号的顺序吗?

linux - 使用 Bash Shell 脚本制作一个简单的饼图

linux - 如何使断点在 bashdb 中工作

linux - 如何在 shell 中使用包含数字属性的属性文件