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


当前回答

我更喜欢使用egrep,尽管在我的测试中,您的方法工作得很好(尽管在我的测试中没有引号)。这个方法也奏效了:

egrep -v "^(\r?\n)?$" filename.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

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

这里,grep -e表示grep的扩展版本。'^$'表示^(行首)和$(行尾)之间没有任何字符。'^'和'$'是正则表达式字符。

因此,命令grep -v将打印所有不匹配此模式的行(^和$之间没有字符)。

这样,空行就被消除了。

我努力尝试,但这似乎工作(假设\r在这里咬你):

printf "\r" | egrep -xv "[[:space:]]*"