Finding files which contain a certain string using find (1) and grep (1)
I use
grep "some string" . -R
and it working faster
p.s.
More complex use case
grep -HiRE "some string|other string" . #H for file printing, i for case-insensitive, R for recursive search, E for regex
To read param i explanation
grep --help | grep -- -i
That's because you're feeding grep
a stream of text which just happens to contain filenames. Since you provided no filenames as arguments to grep, it cannot be expected to deduce what file a matched line came from. Use xargs
:
find . -type f -print | xargs grep "some string"
Since you have GNU find/xargs, this is a safer way for xargs to read filenames:
find . -type f -print0 | xargs -0 grep "some string"
If you only want the filenames that have a matching line without showing the matching line:
find . -type f -print0 | xargs -0 grep -l "some string"
I often search for source code in complex folder structures and I find useful using:
cd /your/folder/
grep -rHino "your string"
With those parameters, without using find, I obtain the file full path and the line number that contains the specified string.
It is also easy to remember because it BASHes through your search like a rHino :)
I will show how this works with a quick example.
Let's display the content of a file using cat:
jeeves ~ # cat fw.stop
#!/bin/sh
echo "Stopping firewall and allowing everyone..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
And let's search recursively for all the files containing the string "iptables -P":
jeeves ~ # grep -rinHo "iptables -P"
fw.stop:9:iptables -P
fw.stop:10:iptables -P
fw.stop:11:iptables -P
As you can see in the output we have filename:hit row:searched string
Here's a more detailed description of the parameters used:
-r For each directory operand, read and process all files in that directory, recursively. Follow symbolic links on the command line, but skip symlinks that are encountered recursively. Note that if no file operand is given, grep searches the working directory. This is the same as the ‘--directories=recurse’ option.
-i Ignore-case.
-n Prefix each line of output with the 1-based line number within its input file. (-n is specified by POSIX.)
-H Print the file name for each match. This is the default when there is more than one file to search.
-o Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line. Output lines use the same delimiters as input, and delimiters are null bytes if -z (--null-data) is also used (see Other Options).