简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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