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
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
Hi, I use a script called "mgrep" for this:
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
for a in `find . -type f`; do file -bi $a | grep "^text" 2>&1 >/dev/null && grep -l "$1" $a; done;
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
Problem is the space, so your grep is searching
/root/volumes AND *txt
should be
/root/volumes AND *txt
should be
grep -lr "string" /root/volumes/*txt
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-
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"
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Thanks for the points!
By the way, a version of the second command which handles filenames with spaces in is:
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
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!
Open in new window