grep ignoring pipe when aliased to 'grep -R'

I’m trying to pipe the output of a grep search into the input of another grep.
Such as:

grep search_query * | grep -v but_not_this

But the second grep is not using the output of the previous search. It looks like the second grep is just using * instead. For example,

grep lcov *                                                                                          
tst/bits/$(call func_report_lcov)
tst/drivers/$(call func_report_lcov)

But when I want to filter out the results containing “call”,

grep lcov * | grep -v call

Grep gives me every single line in my workspace that doesn’t contain “call”.

Environment Info:

  • This is happening in both bash and fish
  • I have aliased the grep command like so alias grep='grep -nR --color=always'

Anything else I might be missing?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The alias is what is causing it. From man grep, the -R option causes grep to “read all files under each directory, recursively”. Hence, the part after the pipe ignores the output from the first grep, and instead greps through all files recursively from the current directory.

You can bypass the alias and use vanilla grep with \grep. Hence the following should give you what you expect.

grep lcov * | \grep -v call

However, I personally think that putting -R in the alias is confusing.

Solution 2

Interesting. This appears to be correct, looks like the devil’s in the details.

grep "search_query" *

could be different than

grep search_query *

which could be different again from

grep 'search_query' *

Try this:

grep search_query * > /tmp/foo
grep -v but_not_this /tmp/foo

Does the file /tmp/foo contain what you want?
Does grep -v but_not_this give the answer you want?
replace grep with \grep to unalias it it and see if that works.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply