What grep command will include the current functio

2019-02-21 07:41发布

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;

标签: shell grep
9条回答
唯我独甜
2楼-- · 2019-02-21 08:25

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!

查看更多
孤傲高冷的网名
3楼-- · 2019-02-21 08:42

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.

查看更多
贼婆χ
4楼-- · 2019-02-21 08:42

Here is an imperfect solution. It has the following flaws:

  1. It requires a tool called ctags
  2. Consequently, it works for C files, or any languages that ctags supports, but not beyond that
  3. It displays all C function headers, no matter what. This is the biggest problem with my script, you might be able to find a way to overcome it.

I called my script `cgrep.sh', which has the following syntax:

cgrep.sh search-term files...

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:

#!/bin/sh

# Grep, which includes C function headers
# cgrep term files*

TERM=$1                             # Save the search term
shift

ctags "$@"                          # produces the tags file
sed -i.bak 's:^.*/^:^:;s:/$::' tags # Prepare the tags file for grep
                                    # Original contents is backed up to tags.bak
grep -f tags -e $TERM "$@"          # Grep both headers and search term
rm tags tags.bak                    # Clean up
查看更多
登录 后发表回答