How to recursively search directories for a pattern and just print out file names and line numbers

grep

Currently I am using grep as follows:

grep -lr <PATTERN> .

This gives me the following output, containing a list of all files whose contents (not name) contain :

./path/to/file1
./path/to/file2
...

This is okay but knowing the line numbers would be useful. The following output would be ideal but having gone through the man page for grep, I can't seem to figure out the right switches:

./path/to/file1 15, 22, 54
./path/to/file2 16, 17
...

Is this possible with grep or some other tool?

Best Answer

ack does something similar by default. you can use

$ ack blah
path/to/blah
16: blah blah
19: blah blah blah

path/to/more/blah
21: blahness

If you just want the file names that match you can say ack -l. ack -lc will give you number of matches per file.

Related Question