Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

5 Answers

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.

share|improve this answer
add comment

Grep has options to print just file names, or just file names and match counts, or matching lines (possibly with file names and line numbers), but not to condense multiple matches on one line.

You can filter the grep output, or use another tool such as awk.

find . -type f -exec awk 'FNR==1 {if (found) print ""; found=0}
                          /PATTERN/ { if (!found) printf("%s", FILENAME);
                                      printf(" %d", FNR);
                                      found=1 }
                          END {if (found) print ""}' {} +
share|improve this answer
add comment
grep -rins <pattern> *

Does that do what you're looking for?

In case you have more complex pattern, for instance when using egrep, it might be usefull to use egrep -rinos <pattern> * instead.

To further increase readability, add --color to the parameter list. Personally, I have that in my .zshrc:

export GREP_OPTIONS="--color"
share|improve this answer
1  
-i ignores cases, which wasn't asked for. –  user unknown Apr 13 '11 at 17:44
add comment

if you want to search an full tree try

find . -exec grep -n blah  {} /; -ls  

or does similar

find . -exec grep -n blah {} /; -print
share|improve this answer
add comment

grep's -H tag includes the filename, grep's -n tag prints the line number. If you want to only list the first match and the filename, you can use -l.
To exclude additional info you could pipe to sed while getting both the line number and the file name you could pipe to sed.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.