简体   繁体   English

Grep表达式排除了我想要的一些匹配项

[英]Grep expression is excluding some matches that I want

I'm working on a program that extracts the comments from a bash file and outputs them to a new file. 我正在开发一个程序,该程序从bash文件中提取注释并将其输出到新文件。

I need to ignore #'s encased in ' ' or " " quotations which I think I have done correctly. 我需要忽略用'或“引号引起来的#,我认为我做对了。

grep -oe "[^\'\"\\]#[^\'\"].*" somefile >> somecomments

This extracts comments that are preceded by some text fine, eg 这将提取注释,然后加上一些精细的文本,例如

echo Sum: $Sum    # Displays the sum

will be converted to "# Displays the sum" in the output file. 将在输出文件中转换为“#显示总和”。 The problem is that lines beginning with # are now excluded for some reason eg 问题是由于某种原因,现在排除了以#开头的行,例如

# Name
# Date

will not show up in the output file at all. 完全不会显示在输出文件中。

How do I fix my expression so that I can still exclude quotations in front of the # but have it extract lines beginning with #? 如何修复表达式,以便仍然可以排除#前面的引号,但是提取出以#开头的行?

Check if following works for you: 检查以下内容是否对您有用:

grep -oe "[^\'\"\\]#[^\'\"].*" -e "^#.*" somefile >> somecomments

But as one of the comment say, you will have to take care of many exceptions. 但是,正如评论之一所说,您将不得不处理许多例外情况。

What if there is a statement like 如果有这样的声明怎么办

echo '<space> ########### Following code does this #########<space>'

You shall have to take all those chances in mind. 您必须牢记所有这些机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM