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;
Here you go:
You just need git. The files being searched do not need to be part of a git repo. But if they are, then omit
--no-index
and get an instant speed boost!Unfortunately, no. This feature does not exist in
grep
nor does it exist inack
(which is ab improvedgrep
replacement).I really do wish this existed, though. It would come in handy. Someone did take a shot at implementing it a while back, but it doesn't look like their patch ever got accepted (or was ever even posted online, strangely). You can try emailing him and see if he still has the code and still wants to get an option to show C functions into
grep
.You could write a regular expression to match a C function, but I bet that'd be one monster of a regexp.
Here is an imperfect solution. It has the following flaws:
ctags
I called my script `cgrep.sh', which has the following syntax:
Cgrep.sh works by relying on
ctags
to produce a list of search patterns for function headers. We can then search for both the function headers and the search term. Without further ado, here is cgrep.sh: