How I can make the grep command locate certain words in the files specified by the routes found by the locate command?
locate my.cnf | grep user
(I want that grep command search the word "user" on the files found for locate command)
How I can make the grep command locate certain words in the files specified by the routes found by the locate command?
locate my.cnf | grep user
(I want that grep command search the word "user" on the files found for locate command)
If your search results are sure to return paths with no spaces, you could use xargs like this:
locate my.cnf | xargs grep user
However you should get in the habit of protecting yourself to handle the case where a path or filename might contain a space by telling xargs to use null as a separator and telling locate (or whatever program you are using to return strings) to also send that as the separator like this:
locate -0 my.cnf | xargs -0 grep user
This would work even if your path included blanks like /name with space/my.cnf.
locate my.cnf | xargs grep -H user so that the output lines report which file(s) the match was found in.
locate -0 my.cnf | xargs -0 -r grep user in case any filenames had spaces etc in them. Note that not all versions of locate support the -0 or --null option for null-terminated output. mlocate does. IIRC, GNU locate does too.
If I understand correctly, you could do something like this:
#!/bin/sh
typeset what1=$1
typeset what2=$2
[ "$#" -eq 2 ] || { echo "Two arguments expected"; exit 1; }
locate ${what1} | while read file; do
grep ${what2} ${file} /dev/null
done
This searches the files matching the locate argument (what1) for a string that matches what2. The dev/null argument forces grep to report the file name of a match.
/dev/null, although you can also echo the file name yourself.
echo ${file} but I dislike having to spawn yet another process just for that purpose.
echo so it does not spawn a process anyway.
grep -q "#what2" && [other action]. As I said, that is an interesting hack however and I'll remember it, may come in handy although I tend to dislike things that their function isn't readily apparent to somebody reading the code.
One-liner:
for file in $(locate my.cnf) ; do grep -r user "$file" ; done
If you want to search pattern in files under the directory name you got from locate then -r will take care of it otherwise remove -r.