Linux: Find text in a large number of files

If you need to find a string in a file, you would typically use:

1
grep -H "string to find" filename.ext

However, grep doesn’t handle a large number of files well. If you specify

1
grep "string" *

or even

1
<em>grep "string" `find ./`</em>

you may find yourself facing this error:

1
bash: /bin/grep: Argument list too long

If you need to search for a string in a lot of files then you can use a simple bash script to do the searching for you.

In this sample, I am looking for a string “sample string” in a directory named “./sample/”:

1
for i in `find ./sample/`; do grep -H "sample string" $i; done

This uses the find command to do the searching. It actually returns a list of filenames, which we can then grep one-by-one. The -H option tells grep to let us know the filename it found the string in so we can go right into that file to find the location of it.

Join RSS Readers other readers by subscribing to my RSS feed! RSS Logo

Share on Twitter Save to Delicious Stumbleupon Share on Facebook Reddit Other services
Short URL: http://sysbash.com/3w
Last updated: September 17th, 2006