March 08, 2013

Linux : look for a string pattern in files in a particular directory and sub directories

Say you want to search for a string pattern in all files included in a directory, and even in its subdirectories. Well, here is the magic command :

find /directory/where/to/look/for -exec grep -nH "my string to look for" {} \;


The command is pretty self explanatory :

/directory/where/to/look/for
The ditectory where you will lokk for files, including all of its sub-directories

-nH
the 'n' option will print line numbers, and 'H' file paths.

Add a number in those options, and bash will print out 'x' the x lines before and after the line matching the pattern (i.e. -nH5 will print out five lines after and before matching line)


"my string to look for"

The pattern to look for. Quotes are only mandatory if your search pattern includes spaces.

You can of course use other find and grep options, i.e. find -name *.xml to filter only xml files.

Example :

 find . -exec grep -H 10108 {} \;

./blabla.text:7:ds10108
Binary file ./jre1.6.0_21/win/bin/fontmanager.dll matches
Binary file ./jre1.6.0_21/win/lib/rt.jar matches


No comments:

Post a Comment