我在Linux中尝试了grep -v '^$',但没有工作。该文件来自Windows文件系统。


当前回答

Use:

grep pattern filename.txt | uniq

其他回答

Use:

$ dos2unix file
$ grep -v "^$" file

或者简单地awk:

awk 'NF' file

如果你没有dos2unix,那么你可以使用像tr这样的工具:

tr -d '\r' < "$file" > t ; mv t "$file"

试试下面的方法:

grep -v -e '^$' foo.txt

e选项允许正则表达式模式进行匹配。

^$周围的单引号使它适用于shell。其他shell只接受单引号或双引号。

更新:这适用于一个有空行或“全空白”的文件(如windows行带\r\n样式的行结束符),而上面只删除有空行和unix样式行结束符的文件:

grep -v -e '^[[:space:]]*$' foo.txt
grep -v "^[[:space:]]*$"

The -v makes it print lines that do not completely match

===Each part explained===
^             match start of line
[[:space:]]   match whitespace- spaces, tabs, carriage returns, etc.
*             previous match (whitespace) may exist from 0 to infinite times
$             match end of line

〇运行代码

$ echo "
> hello
>       
> ok" |
> grep -v "^[[:space:]]*$"
hello
ok

要了解更多关于这是如何/为什么工作的,我建议阅读正则表达式。http://www.regular-expressions.info/tutorial.html

文件中的行中有空白字符吗?

如果是,那么

grep “\S” 文件.txt

否则

握。文件.txt

得到的答案: https://serverfault.com/a/688789

如果在一行中有多个空行序列,并且每个序列只希望有一个空行,请尝试

grep -v "unwantedThing" foo.txt | cat -s

Cat -s抑制重复的空输出行。

你的输出会从

match1



match2

to

match1

match2

原始输出中的三个空行将被压缩或“压缩”为一个空行。