-1

I use this command to find all files of a given type in a given directory which that contain a given string:

find /path/to/dir/ -name "*.php" -exec grep -l "my string" {} \;

However it only returns the file names. Is it possible that it could also return all line numbers where matches were found and (for bonus points) a preview of each line? If so, would this be significantly slower?

Secondly, how could I make it work with multiple file types?

tink
  • 14,342
  • 4
  • 46
  • 50
cronoklee
  • 6,482
  • 9
  • 52
  • 80
  • I'm going to leave this open as the "duplicate" answers do not restrict by filetype and are many hundreds of times slower than the answer below. – cronoklee Feb 18 '21 at 09:49

1 Answers1

0
find /path/to/dir/ -name "*.php" -or -name "*.py" -exec awk '/my string/ { printf "%s - %s - %s\n\n",FILENAME,FNR,$0 }' '{}' +

Use -or with find to search multiple file types and then use awk to print the data required.

Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
  • Amazing! Thank you. The multiple file types doesnt seem to work however. It returns nothing if I include `-or -name "*.py"` but works perfectly without it. Could I add line breaks to the output? – cronoklee Feb 17 '21 at 18:26
  • 1
    OK. I've amended the answer to add an extra line feed after each line. What version of find are you using? – Raman Sailopal Feb 18 '21 at 08:43