Linux 如何删除文件内容里的空白行
删除文件内容里的空白行,找到3个方法,方法1是使用vi编辑器,方法2是使用sed命令,方法3是使用tr命令。
鉴于本文的命令操作具有一定的风险性,在实际工作中,若非必要就不要用了,若是一定要用,那么第一步就是要备份原始文件。
方法1: 使用vi编辑器
在末行模式输入这个命令并执行: :g/^$/d。

执行:g/^$/d前

执行:g/^$/d后
方法2: 使用sed命令
# 谨慎执行这个命令,执行前一定要先备份原始文件
# 因为执行这个命令后会把修改直接写入到原始文件里
sed -i '/^$/d' 文件名
这个命令的使用详情如下
# 这一步非常重要,为了防止意外的出错,需备份原始文件
root@hgdm:~/examples# cp blanks.txt blanks_backup.txt
root@hgdm:~/examples# cat blanks.txt
the
best
way
out
is
always
through
# 这里没有直接使用sed -i把修改写入到原始文件,而是输出到终端看一下结果如何,是否符合预期
root@hgdm:~/examples# sed '/^$/d' blanks.txt
the
best
way
out
is
always
through
# 若sed的执行结果符合预期,则使用sed -i把修改写入到原始文件
root@hgdm:~/examples# sed -i '/^$/d' blanks.txt
root@hgdm:~/examples# cat blanks.txt
the
best
way
out
is
always
through

sed -i '/^$/d' blanks.txt
可能有人会疑惑,为何不直接重定向到原始文件保存。不要这样做。不要使用以下命令,因为会导致原文件blanks.txt的内容被清空
sed '/^$/d' blanks.txt > blanks.txt
以下是这个危险命令的执行结果截图

不要执行sed '/^$/d' blanks.txt > blanks.txt,因为会清空原文件的内容
方法3: 使用tr命令
cat 文件名 | tr -s '\n'
这个命令的使用详情如下
# 这一步非常重要,为了防止意外的出错,需备份原始文件
root@hgdm:~/examples# cp blanks.txt blanks_backup.txt
root@hgdm:~/examples# cat blanks.txt
the
best
way
out
is
always
through
root@hgdm:~/examples# cat blanks.txt | tr -s '\n'
the
best
way
out
is
always
through
# 为何不直接执行这个命令:cat blanks.txt | tr -s '\n' > blanks.txt?不要执行这个命令,这个命令很危险,会造成原始文件blanks.txt内容的丢失。
# 把tr命令的输出结果写入到一个临时文件
root@hgdm:~/examples# cat blanks.txt | tr -s '\n' > temp.txt
# 查看临时文件的内容
root@hgdm:~/examples# cat temp.txt
the
best
way
out
is
always
through
# 把临时文件的内容写入到原来的文件blanks.txt
root@hgdm:~/examples# cat temp.txt > blanks.txt
root@hgdm:~/examples# cat blanks.txt
the
best
way
out
is
always
through

cat blanks.txt | tr -s '\n'
可能有人会疑惑,为何不直接使用以下命令?因为这个命令会导致原始文件内容被清空了。
# 不要执行这个命令,这个命令的执行结果是,原始文件blanks.txt的内容被清空了
cat blanks.txt | tr -s '\n' > blanks.txt
以下是这个危险命令的执行结果截图

不要执行cat blanks.txt | tr -s '\n' > blanks.txt,因为这个命令会清空原文件的内容