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;
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With