Find files containing a pattern

Using grep

grep [pattern] . -riHn

This will recursively find all files under the current directory (and it's subdirectories) that contain the given pattern. The i switch makes the search ignore character case, the H switch includes the filenames in the output and the n switch gives the line numbers.

Using find and grep

find [path] -name [filename] -exec grep -iHn [pattern] {} \;

This will recursively search the directory [path] for files named [filename] that contain the [pattern]. For each match found, it will output the line containing the pattern. As above, the i switch makes the search ignore character case, the H switch includes the filenames in the output and the n switch gives the line numbers.

For example, find . -name "*.html" -exec grep -iHn mindSpill {} \; will recursively search the current directory for any HTML files containing the word "mindspill".

You can leave off the -name switch to search all files in the given directory.

Another useful grep switch is l which will suppress normal output and instead print the name of each input file from which output would normally have been printed. The i switch will make grep ignore the case of the pattern.

xargs

The combination of the find command, pipes and xargs is a very useful one - it can be used to perform a command on/with each of the found files. See xargs for details of how to use xargs.

Last modified: 19/02/2007 Tags: (none)

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top