7

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?

5

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.

2

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 ""}' {} +
1
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"
  • 1
    -i ignores cases, which wasn't asked for. – user unknown Apr 13 '11 at 17:44
0

if you want to search an full tree try

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

or does similar

find . -exec grep -n blah {} /; -print
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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