Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

You can use find:

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

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

Your Answer


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.