我正在尝试使用sed删除空行:

sed '/^$/d'

但我运气不佳。

例如,我有这样几行:

xxxxxx


yyyyyy


zzzzzz

我希望它是这样的:

xxxxxx
yyyyyy
zzzzzz

这个的代码应该是什么?


当前回答

你可以说:

sed -n '/ / p' filename    #there is a space between '//'

其他回答

你可以说:

sed -n '/ / p' filename    #there is a space between '//'

在“空”行中可能有空格或制表符。使用POSIX类和sed删除所有只包含空格的行:

sed '/^[[:space:]]*$/d'

一个使用ERE的短版本,例如gnu sed:

sed -r '/^\s*$/d'

(注意sed不支持PCRE。)

我相信这是最简单和最快的方法:

cat file.txt | grep .

如果你需要忽略所有空白行,那么试试这个:

cat file.txt | grep '\S'

例子:

s="\
\
a\
 b\
\
Below is TAB:\
    \
Below is space:\
 \
c\
\
"; echo "$s" | grep . | wc -l; echo "$s" | grep '\S' | wc -l

输出

7
5

对我来说,使用FreeBSD 10.1和sed只工作了这个解决方案:

sed -e '/^[     ]*$/d' "testfile"

[]里面有空格和制表符。

测试文件包含:

fffffff next 1 tabline ffffffffffff

ffffffff next 1 Space line ffffffffffff

ffffffff empty 1 lines ffffffffffff

============ EOF =============

这也适用于awk。

awk '!/^$/' file
xxxxxx
yyyyyy
zzzzzz