Asked • 07/27/19

grep regex to ignore comment at end of line?

I'm trying to grep through a lot of old PowerBASIC source files in search of a variable, but I'm having trouble getting `grep` to avoid matching references to the variable in the end-of-line comments. For example: ANGLE = 40 ' THIS IS A COMMENT ABOUT ANGLE'S VALUE FOO = 3/ANGLE ' ANGLE CAN APPEAR ON RIGHT SIDE AS WELL DELTA = 35 ' ANGLE AND DELTA AREN'T FRIENDS Initially I was using: # grep "\\bANGLE\\b.*'" SRC_FILE.BAS But -- besides ignoring lines with no comments -- it also prints out lines of code which don't use `ANGLE` at all (such as the `DELTA` line). This is because those lines happen to also have a *single* apostrophe (`'`) in their comments (i.e. `AREN'T`). I thought of piping the output to remove the lines I don't want with: # grep "\\bANGLE\\b" SRC_FILE.BAS | grep -v "'.*\\bANGLE\\b" But unfortunately it also removes the lines of code I do want that just happen to have "`ANGLE`" in their comments. How do I get grep to match the lines of actual code involving `ANGLE` and ignore those lines with *only* matches in the comments?

1 Expert Answer


Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.