How can I search all files under a specific directory that contian a specific string sequence like "superuser"

i.e. search for all files in the current directory and sub-directories (recursively) if they contain the world "superuser"


grep's -R option does this:

grep -R "superuser" .

EDIT: to search only .mp3 files and return their names (not the matched content, since they aren't text files anyway), use find to get a list of .mp3's and then use xargs to pass them to grep -l:

find . -name "*.mp3" -print0 | xargs -0 grep -l "superuser"

If your version of find supports -exec ... + (and at least recent OS X's do), you can have find run grep directly:

find . -name "*.mp3" -exec grep -l "superuser" {} +
  • Useful additional options: -F to speed up fixed-string searches; -l just show filenames, not matching lines (useful for binary files); -m 1 stop reading file after 1st match. – RedGrittyBrick Feb 18 '12 at 19:04
  • how about for a list of files with a .mp3 extension? – user27449 Feb 18 '12 at 21:57
  • @RedGrittyBrick: Agree about -l and -m1, but I disagree about -F being faster (despite that being what the F stands for). Traditional grep actually ran fastest (on large/many files) in -E mode, since that compiled the pattern into a DFA -- long startup time for the compilation, but once that was done it was very fast. -F mode might be fast if your version of grep uses the Boyer-Moore algorithm (instead of the old naive algo), but IME most modern greps are adaptive and will choose the fastest mode automatically, no matter what flag you use. – Gordon Davisson Feb 19 '12 at 1:09
  • @Gordon: Quite right, my mistake. – RedGrittyBrick Feb 19 '12 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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