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
You could write a script that grep -v
s into a temporary file and then diff -p
s that with the original. That way diff
would find the lines that grep
removed (i.e. the lines that you want), and you would get the exact same function matching.
Here you go:
git grep --no-index -n -p 'return'
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!
Assuming you are searching for foobar:
grep -e "^\w.*[(]" -e foobar *.h *.cpp | grep -B 1 foobar
greps for all functions and all foobar, then greps for just foobar and the preceding lines - which will be only foobars and the containing functions.
tested on cygwin on windows version
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.
As with most text processing operations, it's trivial with awk:
$ awk -v re='return' '/^[[:alpha:]]/{f=FNR"-"$0} $0~re{printf "%s\n%d:%s\n--\n",f,FNR,$0; f="" }' file
1-int func1(int x, int y)
3: return x + y;
--
5-int func2(int x, int y, int z)
9: return tmp;
--
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.
Unfortunately, no. This feature does not exist in grep
nor does it exist in ack
(which is ab improved grep
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.