Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find files containing a string using egrep

Tags:

linux

grep

find

I would like to find the files containing specific string under linux. I tried something like but could not succeed:

find . -name *.txt | egrep mystring

like image 302
Tolga Avatar asked Sep 01 '09 13:09

Tolga


People also ask

How do I find all files containing specific text?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.

How do I search for a file in a string?

Use the grep command to search the specified file for the pattern specified by the Pattern parameter and writes each matching line to standard output. This displays all lines in the pgm. s file that begin with a letter.

How do you search all the files in a directory for a string?

You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

How do I search for a file containing text in Unix?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in.


1 Answers

Here you are sending the file names (output of the find command) as input to egrep; you actually want to run egrep on the contents of the files.

Here are a couple of alternatives:

find . -name "*.txt" -exec egrep mystring {} \;

or even better

find . -name "*.txt" -print0 | xargs -0 egrep mystring

Check the find command help to check what the single arguments do.
The first approach will spawn a new process for every file, while the second will pass more than one file as argument to egrep; the -print0 and -0 flags are needed to deal with potentially nasty file names (allowing to separate file names correctly even if a file name contains a space, for example).

like image 57
Paolo Tedesco Avatar answered Sep 28 '22 02:09

Paolo Tedesco