Question

My code

$  *.php | grep google

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

Was it helpful?

Solution

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)

OTHER TIPS

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.

grep -RH "google" *.php

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

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

Use "man grep" to see other features.

for i in $(ls *.php); do  grep -n --with-filename "google" $i; done;
find . -name "*.php" -print | xargs grep -n "searchstring"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top