linux/unix下如何删除文本文件中的空行,使用sed、awk、grep

如何使用linux 命令行删除文本文件中的空行?

这类似于我们在上一篇文章中介绍的如何删除包含指定字符串的文本文件的方式。我们仍然可以使用sed命令,awk命令和grep命令来完成此操作。


让我们在下面详细查看操作示例。

以下内容是测试文件的内容,我们将使用以下内容进行示例演示。

hello, this is an example of deleting empty lines in a text file.

Use the sed command to delete empty lines.

Use the awk command to delete empty lines.

Use the grep command to delete empty lines.

使用awk命令删除文件中的空行

在下面的示例中,我们将使用awk命令NF变量来检测当前行中的字段数。如果数字为0,则表示当前行为空行。

➜  ~ awk '{if(NF>0) {print $0}}' text.log

# OR

➜  ~ awk '!/^$/' text.log



您使用 awk 'NF' test.log 命令也达到同样的目的。

使用sed命令删除文件中的空行

在下面的示例中,我们将使用sed命令正则表达式来检查当前行是否为空白。如果当前行为空,请删除当前行。

➜  ~ sed '/^$/d' text.log


使用grep命令删除文件中的空行

在以下示例中,我们将使用grep命令-v选项排除匹配的空行,然后使用“>”将数据输出到新文件。

➜  ~ grep -v '^#39; text.log

➜  ~ grep -v '^#39; text.log > newFile.log


举报
评论 0