2

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

1 Answers1

4
grep -Rn "your_string" *

Should do the trick.

Nunus
  • 56