Show filename and line number in grep output

grep -rin searchstring * | cut -d: -f1-2

This would say, search recursively (for the string searchstring in this example), ignoring case, and display line numbers. The output from that grep will look something like:

/path/to/result/file.name:100: Line in file where 'searchstring' is found.

Next we pipe that result to the cut command using colon : as our field delimiter and displaying fields 1 through 2.

When I don't need the line numbers I often use -f1 (just the filename and path), and then pipe the output to uniq, so that I only see each filename once:

grep -ir searchstring * | cut -d: -f1 | uniq

I think -l is too restrictive as it suppresses the output of -n. I would suggest -H (--with-filename): Print the filename for each match.

grep -Hn "search" *

If that gives too much output, try -o to only print the part that matches.

grep -nHo "search" * 

Tags:

Grep

Awk