What grep command will include the current function name in its output?

前端 未结 9 2064
夕颜
夕颜 2021-01-07 18:08

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

相关标签:
9条回答
  • 2021-01-07 18:13

    You could write a script that grep -vs into a temporary file and then diff -ps 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.

    0 讨论(0)
  • 2021-01-07 18:14

    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!

    0 讨论(0)
  • 2021-01-07 18:21

    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

    0 讨论(0)
  • 2021-01-07 18:22

    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.

    0 讨论(0)
  • 2021-01-07 18:22

    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.

    0 讨论(0)
  • 2021-01-07 18:24

    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.

    0 讨论(0)
提交回复
热议问题