Grep list filename and line number

Hi 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 a awk?


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

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 like using:

grep -niro 'searchstring' <path>

But that's just because I always forget the other ways and I can't forget Robert de grep - niro for some reason :)

链接地址: http://www.djcxy.com/p/74310.html

上一篇: 如何'grep'连续的流?

下一篇: Grep列表文件名和行号