Link to home
Start Free TrialLog in
Avatar of electricd7
electricd7

asked on

How to search a directory recursively for specific files containing a text string in linux / unix

Hello,

I would like a command to search a directory recursivly for all .txt files containing the string "string".  I have tried to accomplish this using grep, but it is searching more than just .txt files.  Here is the command I have tried, but its not working correctly:

grep -lr "string" /root/volumes/ *txt
Avatar of icenick
icenick
Flag of Israel image

Hello,

I would go first for "find".

I would search the files with the command find and then use xargs to grep the string you want.

I attached a code snippet.

Good Luck!
find /path/ -type f -name "*.txt" | xargs grep "string"

Open in new window

Avatar of Gerwin Jansen
Hi, I use a script called "mgrep" for this:

for a in `find . -type f`; do file -bi $a | grep "^text" 2>&1 >/dev/null && grep -l "$1" $a; done;

Open in new window


Searches from current folder in all subfolders for string given as a parameter, like this:

mgrep <string>

It will print all text files that match
Avatar of Tintin
Tintin

Problem is the space, so your grep is searching

/root/volumes AND *txt

should be
grep -lr "string" /root/volumes/*txt

Open in new window

Hi,
Try
#grep -i string */*.txt

If you want to put the results on a file add >myoutput.log at the end of the command...

#grep -i string */*.txt>myoutput.log

-hope helps-
find . -type f | xargs grep -l "string"

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of simon3270
simon3270
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for the points!

By the way, a version of the second command which handles filenames with spaces in is:
find /root/volumes -type f -print0 | xargs -0 file | awk -F: '$2 ~ /text/{printf "%s%c",$1,0}' | xargs -0 grep "string" /dev/null

Open in new window