使用sed删除空行

本文探讨了如何使用sed命令在Linux或Unix环境中删除文本文件中的空行。通过分享不同的sed命令示例,解释了处理包含空格或制表符的“空”行的方法,并提到了与其他工具如grep的结合使用。
摘要由CSDN通过智能技术生成

本文翻译自:Delete empty lines using sed

I am trying to delete empty lines using sed: 我试图使用sed删除空行:

sed '/^$/d'

but I have no luck with it. 但我没有运气。

For example, I have these lines: 例如,我有这些行:

xxxxxx


yyyyyy


zzzzzz

and I want it to be like: 我希望它像:

xxxxxx
yyyyyy
zzzzzz

What should be the code for this? 应该是什么代码?


#1楼

参考:https://stackoom.com/question/16s8Y/使用sed删除空行


#2楼

sed '/^$/d' should be fine, are you expecting to modify the file in place? sed '/^$/d'应该没问题,您是否希望修改文件到位? If so you should use the -i flag. 如果是这样,你应该使用-i标志。

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve. 也许那些行不是空的,所以如果是这样的话,看看这个问题从txtfiles中删除空行,从行的开头和结尾删除空格我相信这是你想要实现的。


#3楼

You may have spaces or tabs in your "empty" line. 您的“空”行可能包含空格或制表符。 Use POSIX classes with sed to remove all lines containing only whitespace: 使用带有sed POSIX类删除仅包含空格的所有行:

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

A shorter version that uses ERE, for example with gnu sed: 使用ERE的较短版本,例如使用gnu sed:

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

(Note that sed does NOT support PCRE.) (请注意,sed的支持PCRE)。


#4楼

你可以说:

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

#5楼

With help from the accepted answer here and the accepted answer above, I have used: 此处接受的答案和上面接受的答案的帮助下,我使用了:

$ sed 's/^ *//; s/ *$//; /^$/d; /^\s*$/d' file.txt > output.txt

`s/^ *//`  => left trim
`s/ *$//`  => right trim
`/^$/d`    => remove empty line
`/^\s*$/d` => delete lines which may contain white space

This covers all the bases and works perfectly for my needs. 这涵盖了所有基础,完美地满足了我的需求。 Kudos to the original posters @Kent and @kev 感谢@Kent和@kev的原创海报


#6楼

您也可以使用“grep”执行类似的操作:

egrep -v "^$" file.txt
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值