I run diff
with the -p
option so the output will include the name of the function where each change occurred. Is there an analogous option for grep
? If not, what other command could I use instead?
Instead of -B
to show a fixed number of context lines that immediately precede a match, I'd like for the match to be preceded by just one line with the most recent function signature, however many lines back it was in the file. If the option I'm looking for were -p
, output might look like this, for example:
$ cat foo.c int func1(int x, int y) { return x + y; } int func2(int x, int y, int z) { int tmp = x + y; tmp *= z; return tmp; } $ grep -p -n -e 'return' foo.c 1-int func1(int x, int y) 3: return x + y; -- 5-int func2(int x, int y, int z) 9: return tmp;
You could write a script that
grep -v
s into a temporary file and thendiff -p
s that with the original. That waydiff
would find the lines thatgrep
removed (i.e. the lines that you want), and you would get the exact same function matching.As with most text processing operations, it's trivial with awk:
The above assumes a function signature is any line that starts with a letter (/^[[:alpha:]]/). If that's not the way your code is written, just tweak to suit.
Actually "grep -p" has been a fixture in AIX for the last two decades from what I can recall. It is out there, and it's just a matter of porting the behaviour over in fresh code.
It's crude, though, and may need help to know that blank lines within a function don't count.
There is no such function in GNU grep, although it has been discussed in the past.
However if your code is under
git
's control,git grep
has an option-p
that will do that.I wrote a script to grep C files and show the C function names and signature along with the results. Based on ctags.
Enjoy. :)
Assuming you are searching for foobar:
greps for all functions and all foobar, then prints filters for just foobar and the preceding lines - which will be only foobars and the containing functions. (tested on ubuntu bash)