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
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With