I want to skip pattern in comments between /* */ or whatever

59 views Asked by At

I want to skip pattern in comments between /* */ or whatever. for example f:

My name is
/*
alex
nice man
*/
alex is a nice man

Command:

git grep "alex" f

Print only:

alex is a nice man

I prefer use with git grep.

1

There are 1 answers

0
Ed Morton On

grep stands for g/re/p i.e. Globally search for a Regular Expression and print the matching string. What you're trying to do is far beyond that simple statement so you should be using awk:

$ awk 'index($0,"/*"){f=1} index($0,"*/"){f=0} !f && /alex/{print}' file
alex is a nice man

While the above will work for the simple example you show, it will fail for other cases such as multiple comments on a line or comments at the start/end of a target line or comment delimiters in other constructs such as within strings.

If you have those cases (e.g. as you could in a C or similar program) then you shouldn't be trying to do this with a text processing tool, you need a language parser, e.g. see https://stackoverflow.com/a/35708616/1745001