tags:

views:

1009

answers:

7

My code

$  *.php | grep google

How can I print the filenames and linenumbers next to each match?

+4  A: 
grep google *.php

if you want to span many directories:

find . -name \*.php -print0 | xargs -0 grep -n -H google

(as explained in comments, -H is useful if xargs comes up with only one remaining file)

cadrian
Does the latter code find subdirectories or master directories?
Masi
You need the name because you may not know which file it was - especially if it is bad break that xargs batched things up and had a single file left over.
Jonathan Leffler
Don't forget that you should use -print0 to find and -0 to xargs if you are working in a directory tree that has names with things like embedded whitespace in them.
Michael Trausch
cadrian
Your first line doesn't print filenames and numbers, the second recurses (which Masi didn't imply). "find . -maxdepth 1 -name \*.php -print0 | xargs -0 grep -nH google" would fit the bill.
DevSolar
A: 

Use "man grep" to see other features.

for i in $(ls *.php); do  grep -n --with-filename "google" $i; done;
J.J.
that won't work - the input file is "stdin" when the command is written this way
Alnitak
You right. Changed the code to work.
J.J.
+4  A: 

You shouldn't be doing

$ *.php | grep

That means "run the first PHP program, with the name of the rest wildcarded as parameters, and then run grep on the output".

It should be:

$ grep -n -H "google" *.php

The -n flag tells it to do line numbers, and the -H flag tells it to display the filename even if there's only file. Grep will default to showing the filenames if there are multiple files being searched, but you probably want to make sure the output is consistent regardless of how many matching files there are.

Alnitak
A: 
find . -name "*.php" -print | xargs grep -n "searchstring"
al
A: 

find ./*.php -exec grep -l 'google' {} \;

Jacer
That gets the file names, but not the line numbers, doesn't it?
Jonathan Leffler
A: 
grep -RH "google" *.php
ghostdog74
+1  A: 

Please take a look at ack at http://betterthangrep.com. The equivalent in ack of what you're trying is:

ack google --php
Andy Lester