I have been using this utility successfully for many years, in many environments. But I notice that in one particular environment it produces very unexpected results.
grep -r 'search-term1' . | grep 'search-term2'
The above code is recursively recursive for all instances of search-term1 in current-dir. Then the results are passed to another grep, which selects only those rows that also contain search-term2. This works exactly as I expected.
grep -r 'search-term1' . | grep -r 'search-term2'
The only difference in the above code is that the -r recursive flag is specified in both grep commands. I would expect that the behavior will not change for this particular case. In the end, the input to the second grep is the input channel, and there is nothing that could be found recursively.
I have successfully used this command for many years in many different environments (both unix and mac-os). However, the very last environment I started working in (unix) violates the above behavior. The second piped grep searches for all instances of search-term2, not only in the input channel, but in all the files in my current directory. Because of this, instead of getting only results containing both search terms, I get all results in current-dir that contain the second search query.
Is there a reason why this particular environment creates this strange behavior? Is there a way to avoid this while maintaining the -r flag?
Reference:
Q: Why do I use the -r flag on channel input?
Ans: grep, , , . . , , .
: , , ( -superior-method-here)?
Ans: , . , , , . , , , -grep-on-pipe , , - .