Show filename and line number in grep output

trev9065 picture trev9065 · Nov 12, 2011 · Viewed 86.5k times · Source

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

Is there a grep flag that will do this for me? I have been trying to use a combination of -n and -l but these are either printing out the file names with no numbers or just dumping out a lot of text to the terminal which can't be easily read.

ex:

  grep -ln "search" *

Do I need to pipe it to awk?

Answer

spokeadoke picture spokeadoke · Nov 12, 2011

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" *