首页 > 编程知识 正文

sed删除空白行,sed删除行尾空格

时间:2023-05-05 09:26:55 阅读:271335 作者:157

本文翻译自: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: 例如,我有这些行:

xxxxxxyyyyyyzzzzzz

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

xxxxxxyyyyyyzzzzzz

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。