Show file name and line number in grep output

I am trying to find rails in my directory using grep. I am looking for a specific word and want to grep print the file name and line number.

Is there a grep flag that will do this for me? I tried to use a combination of -n and -l but it is either listing file names without numbers, or simply outputting a large amount of text to a terminal that cannot be read easily.

eg:

  grep -ln "search" * 

Do I need to pass this to awk?

+74
grep search awk
Nov 12 '11 at 16:15
source share
3 answers

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

 grep -Hn "search" * 

If this gives too much result, try -o only print the part that matches.

 grep -nHo "search" * 
+115
Nov 12 '11 at
source share
 grep -rin searchstring * | cut -d: -f1-2 

This will searchstring search recursively (for the searchstring string in this example), ignoring case, and displaying line numbers. The output of this grep will look something like this:

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

Then we pass this result to the cut command, using a colon : as a field separator and displaying fields 1 through 2.

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

 grep -ir searchstring * | cut -d: -f1 | uniq 
+28
Jul 19 '12 at 17:55
source share

I like to use:

grep -niro 'searchstring' <path>

But this is only because I always forget other ways, and for some reason I cannot forget Robert de grep - niro :)

+10
Oct 26 '16 at 2:04 on
source share



All Articles