unix - Grep: Recursive option produces unexpected behavior when fed pipe-input -


i've been using utility many years, in many environemnts. i'm noticing on 1 particular environment, produces unexpected results.

grep -r 'search-term1' . | grep 'search-term2' 

the above code greps recursively instances of search-term1, in current-dir. results piped grep, selects lines contain search-term2. works expect.

grep -r 'search-term1' . | grep -r 'search-term2' 

the difference in above code -r recursive flag in specified in both grep commands. expect behavior not change particular case. after all, input 2nd grep pipe-input, , there's nothing further found recursively.

i have been using command successfully, many years, in many different environments (both unix , mac-os). however, recent environment started working in (unix), breaks above behavior. second piped grep searches instances of search-term2, not in piped-input, files in current directory. because of this, instead of getting results contain both search-terms, results in current-dir contain 2nd search term.

is there reason why 1 particular environment produces odd behavior? there way can avoid this, while still preserving -r flag?


faq:

q: why using -r flag on piped input?

ans: have grep saved alias, many different options , flags want use default. recursive flag 1 of them. use alias, instead of having type out flags every time.

q: if want search instances matching both search terms, why not (insert-superior-method-here) instead?

ans: you're right. i'm sure there things can change in usual habits workaround issue. however, intellectual curiosity, find out why recursive-greps-on-pipes work intended on environments, not all, , if can somehow resolved.

the -r flag grep changed in grep version 2.11 (release notes implicitly use working directory input if no file arguments given.

if no file operand given, , command-line -r or equivalent option given, grep searches working directory.

you aren't giving second grep file arguments defaults current directory despite there being pipe input.

try grep -r 'search-term1' . | grep -r 'search-term2' - workaround.

grep -r 'search-term1' . | grep -r -d skip 'search-term2' may work around problem.


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -