Unix/Linux: recursively search for files containing a string
grep -Rn "your_string" *
Should do the trick.
Related videos on Youtube
John Goche
Updated on September 18, 2022Comments
-
John Goche over 1 year
Possible Duplicate:
How to Combine find and grep for a complex search? ( GNU/linux, find, grep )I have a directory hierarchy of files (some of which are plaintext and others are binary).
Is there an easy way to recursively search the hierarchy of files and directories for the names of any files which contain a specified string, and print out a list of "path to file name and line number" if possible?
Basically, what I want is more or less the same as the following, except for perhaps with an option to print line numbers are printed as well:
#!/bin/bash # # Recursively search files for pattern specified as argument. # pattern="$1" if [ -z "$pattern" ]; then echo "$0: Unspecified pattern."; exit; fi searchfiles () { for filename in *; do if [ -f "$filename" ]; then { result=`/bin/grep -e "$pattern" "$filename"` if ! [ -z "$result" ]; then echo "File: `pwd`/$filename"; fi } elif [ -d "$filename" ]; then cd "$filename" searchfiles cd .. fi done } searchfiles
OK, as suggested below, I could use recursive grep, but I only need the filename and line number, as printing its contents could be messy if there are many long long lines which then wrap around the terminal when printed, so here was my solution:
grep -Rn index.php * | sed -e 's/ .*//g'
Regards,
John Goche
-
user5249203 almost 12 years(the answer there is
find /path/to/folder/ -print0 | xargs -0 grep -H -n "string"
) -
Alex Allen almost 12 yearsHow does just
find
not work for you?find -name '*string*'
does not do what you need? -
slhck almost 12 yearsHow do you want to print a line number if all you're searching for is filenames which contain that string?
-
user5249203 almost 12 years@Bernhard,slhck: I think the question is poorly worded, from his mention of line-number I deduce that John actually wants to match text in the file content not in its name. John: please edit your question to clarify.
-
user5249203 almost 12 yearsI've edited Q to match my interpretation! Please undo my changes if you disagree. (I think the Q is a dup or at least a minor variation of another Q)
-
-
Daniel Andersson almost 12 yearsSince you are doing recursive search, just give the base directory as argument instead of
*
. With*
, the shell has to expand it and you will miss hidden files and directories in the base directory.