1

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"

1 Answer 1

2

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" {} + 
4
  • 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. Commented Feb 18, 2012 at 19:04
  • how about for a list of files with a .mp3 extension? Commented Feb 18, 2012 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. Commented Feb 19, 2012 at 1:09
  • @Gordon: Quite right, my mistake. Commented Feb 19, 2012 at 12:51

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.