Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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; 
like image 370
Rob Kennedy Avatar asked May 26 '11 05:05

Rob Kennedy


People also ask

Can you grep the output of a command?

Using Grep to Filter the Output of a CommandA command's output can be filtered with grep through piping, and only the lines matching a given pattern will be printed on the terminal. You can also chain multiple pipes in on command. As you can see in the output above there is also a line containing the grep process.

What is grep command with example?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.

What does grep return?

The grep command searches a text file based on a series of options and search string and returns the lines of the text file which contain the matching search string.


2 Answers

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.

like image 183
adl Avatar answered Sep 23 '22 23:09

adl


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!

like image 23
FractalSpace Avatar answered Sep 26 '22 23:09

FractalSpace