删除使用SED文件中的所有评论 [英] Delete all comments in a file using sed

查看:108
本文介绍了删除使用SED文件中的所有评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用SED从文件(#定义)相对于'#'在一个字符串是如何会删除所有评论?

How would you delete all comments using sed from a file(defined with #) with respect to '#' being in a string?

<一个href=\"http://stackoverflow.com/questions/8206280/delete-all-lines-beginning-with-a-from-a-file\">This帮助了很多除了字符串部分。

This helped out a lot except for the string portion.

推荐答案

如果总是意味着评论,可以在一行出现在任何地方(如经过一番code):

If # always means comment, and can appear anywhere on a line (like after some code):

sed 's:#.*$::g' <file-name>

如果你想改变它在的地方,添加 -i 开关:

If you want to change it in place, add the -i switch:

sed -i 's:#.*$::g' <file-name>

这将从任何删除到行的末尾,忽略任何背景。如果你使用任何地方它不是(在字符串等)的注释,它会删除了。

This will delete from any # to the end of the line, ignoring any context. If you use # anywhere where it's not a comment (like in a string), it will delete that too.

如果评论才能开始在一行的开始,做这样的事情:

If comments can only start at the beginning of a line, do something like this:

sed 's:^#.*$::g' <file-name>

如果他们可能会用空格pceded $ P $,但没有别的,这样做:

If they may be preceded by whitespace, but nothing else, do:

sed 's:^\s*#.*$::g' <file-name>

这两个将是一个小更安全,因为他们有可能不会在code删除的有效使用,如在弦。

编辑:

有没有真正的检测东西是否是在一个字符串的好方法。我会使用最后两个如果这将满足你的语言的限制。

There's not really a nice way of detecting whether something is in a string. I'd use the last two if that would satisfy the constraints of your language.

与检测是否在一个字符串是现在的问题是,经常前pressions不能做的一切。有几个问题:

The problem with detecting whether you're in a string is that regular expressions can't do everything. There are a few problems:


  • 字符串可以容易跨行

  • 定期EX pression不能告诉apostrophies和单引号的区别

  • 一个普通的前pression无法比拟的嵌套引号(这种情况下会混淆正则表达式):

  • Strings can likely span lines
  • A regular expression can't tell the difference between apostrophies and single quotes
  • A regular expression can't match nested quotes (these cases will confuse the regex):

# "hello there"
# hello there"
"# hello there"


如果双引号是字符串的定义的唯一途径,双引号将永远不会出现在一个评论,字符串不能跨越多行,尝试这样的事情:

If double quotes are the only way strings are defined, double quotes will never appear in a comment, and strings cannot span multiple lines, try something like this:

sed 's:#[^"]*$::g' <file-name>

这是一个很大的pre-条件,但如果他们都持有,你在企业里。否则,恐怕你是SOL,你会更好的东西如Python,在那里你可以做更高级的逻辑写它。

That's a lot of pre-conditions, but if they all hold, you're in business. Otherwise, I'm afraid you're SOL, and you'd be better off writing it in something like Python, where you can do more advanced logic.

这篇关于删除使用SED文件中的所有评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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