Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How do I recursively view a list of files that has one string and specifically doesn't have another string? Also, I mean looking inside the files, rather than the file names.

share|improve this question
add comment

2 Answers

You can use find:

find . -type f -name "$fileglob" -exec grep -q $word1 {} \; -not -exec grep -q $word2 {} \; -print
share|improve this answer
add comment

Assuming you really do want a string, not a regexp, thus fgrep, then:

fgrep -rl --null desired_string . | xargs -0 fgrep -lv undesired_string --

Recursively (-r) grep for desired_string under the current directory, printing the filenames (-l) and using the filenames from that, repeatedly invoke fgrep (so as to not overfill the space for command-line arguments when invoking it), with -v inverting the sense of the match.

This uses --null to use an ASCII NUL character after each filename, instead of a newline, so that you can handle filenames with spaces in and the like; that plumbs into the -0 given to xargs. Depending upon the Unix variant (Linux, BSD, etc) there might be a short option for --null, but that's less portable. Strictly speaking, --null is not portable, but any modern system's (f)grep should have it.

The -- at the end of the second (f)grep stops (f)grep from looking for options in any following parameters, so even if you have a filename starting with a -, it will still be processed as a filename.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.