What command would I use to find all of the files under the girl directory that have the ascii text “shirt” inside the files, starting from the root directory?
3 Answers
find . -print0 | xargs -0 grep -FH text
Runs faster than either -exec
or grep -r
on my machine.
-
This is the best answer of the (current) three, because it's a more general technique, it's more portable, and doesn't require memorising
find
s funky syntax. It's also more flexible, because you can include any number of other filters between thefind
and thexargs
(by the way, the-print0
and-0
are formally correct, but rarely necessary, and usually a pest to type) Oct 23, 2011 at 19:45 -
1Nice. It won't be faster when there are many binary files, which grep knows how to skip. @norman-gray
-print0
and-0
are always necessary for scripts. They live on past the author and can give "wtf" moments when they don't work correctly. Oct 23, 2011 at 20:11 -
@ShawnJ.Goff Yes, I agree with you about
-print0
in scripts -- it's best to be on one's best behaviour when it's written down for others to see... Oct 30, 2011 at 17:46
grep
is the standard tool for searching for a pattern inside of files. It has an option for searching recursively, which means if it finds a directory, it goes inside and searches in everything in there.
The command would simply be grep -r shirt /path/to/girl/
I also like to add two options that skip files that I know I'm not interested in: --binary-files=without-match
and --devices=skip
.
-
4If you just want a list of files, use
grep -r -l shirt /path/to/girl
. Oct 23, 2011 at 19:31 -
Yes, @keith-thompson 's suggestion is faster, also because it will stop scanning once it finds just one match. Oct 23, 2011 at 20:03
-
Thank you Shawn J. Goff. grep -r shirt /path/to/girl/ worked perfectly!– MaliaOct 23, 2011 at 22:33
As stated by Shawn, using grep -r
might be enough for your needs.
Otherwise a combination of find
and grep
can do the trick:
find . -exec grep -H text '{}' ';'
This allows to refine the search using specific find predicates.
(And -H
option is there so that filenames are printed along with the matched content.)