sed + 删除“#"和一个 sed 命令的空行 [英] sed + remove "#" and empty lines with one sed command

查看:68
本文介绍了sed + 删除“#"和一个 sed 命令的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用一个 sed 命令从文件中删除注释行(如 # bal bla )和空行(没有字符的行)?

THX莉迪亚

解决方案

如果您出于性能原因担心在管道中启动两个 sed 进程,您可能不应该,它仍然非常有效.但是根据您想要进行就地编辑的评论,您仍然可以使用不同的命令(sed 命令,而不是调用 sed 本身)来做到这一点.>

您可以使用多个 -e 参数或使用分号分隔命令,例如(仅其中之一,而不是两者):

sed -i 's/#.*$//' -e '/^$/d' 文件名sed -i 's/#.*$//;/^$/d' 文件名

以下文字记录显示了这一点:

pax>printf '行# 带注释\n\n# 行仅带注释\n' >文件人>猫文件带有注释的第 # 行# 行只有一个注释人>cp 文件 filex ;sed -i 's/#.*$//;/^$/d' filex ;猫文件线人>cp 文件 filex ;sed -i -e 's/#.*$//' -e '/^$/d' filex ;猫文件线

注意即使使用两个 -e 选项,文件是如何就地修改的.可以看到每行都执行了两个命令.带有注释的行首先删除注释,然后删除所有注释,因为它是空的.

另外,原来的空行也被去掉了.

how to remove comment lines (as # bal bla ) and empty lines (lines without charecters) from file with one sed command?

THX lidia

解决方案

If you're worried about starting two sed processes in a pipeline for performance reasons, you probably shouldn't be, it's still very efficient. But based on your comment that you want to do in-place editing, you can still do that with distinct commands (sed commands rather than invocations of sed itself).

You can either use multiple -e arguments or separate commands with a semicolon, something like (just one of these, not both):

sed -i 's/#.*$//' -e '/^$/d' fileName
sed -i 's/#.*$//;/^$/d' fileName

The following transcript shows this in action:

pax> printf 'Line # with a comment\n\n# Line with only a comment\n' >file

pax> cat file
Line # with a comment

# Line with only a comment

pax> cp file filex ; sed -i 's/#.*$//;/^$/d' filex ; cat filex
Line

pax> cp file filex ; sed -i -e 's/#.*$//' -e '/^$/d' filex ; cat filex
Line

Note how the file is modified in-place even with two -e options. You can see that both commands are executed on each line. The line with a comment first has the comment removed then all is removed because it's empty.

In addition, the original empty line is also removed.

这篇关于sed + 删除“#"和一个 sed 命令的空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆