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


当前回答

从文件中读取行排除空行

grep -v '^$' folderlist.txt

folderlist.txt

folder1/test

folder2
folder3

folder4/backup
folder5/backup

结果如下:

folder1/test
folder2
folder3
folder4/backup
folder5/backup

其他回答

Use:

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

或者简单地awk:

awk 'NF' file

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

tr -d '\r' < "$file" > t ; mv t "$file"
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 -v '^$' folderlist.txt

folderlist.txt

folder1/test

folder2
folder3

folder4/backup
folder5/backup

结果如下:

folder1/test
folder2
folder3
folder4/backup
folder5/backup

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

如果是,那么

grep “\S” 文件.txt

否则

握。文件.txt

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

的确,使用grep -v -e '^$'可以工作,但是它不能删除有1个或多个空格的空行。我发现删除空行最简单的答案是使用awk。下面是对上面awk的修改:

awk 'NF' foo.txt

但由于这个问题是为了使用grep,我将回答以下问题:

grep -v '^ *$' foo.txt

注意:^和*之间有空格。

或者你可以用\s来表示空格,就像这样:

grep -v '^\s*$' foo.txt