在 grep 输出中显示文件名和行号

我正在尝试使用 grep 搜索我的 Rails 目录。我正在寻找一个特定的单词,我想 grep 打印出的文件名和行号。

有没有 Grep 旗能帮我这个忙?我一直试图使用的 -n-l的组合,但这些要么打印出的文件名没有数字或只是倾倒了大量的文本到终端不容易阅读。

例如:

  grep -ln "search" *

我需要用管子把它吹走吗?

108760 次浏览

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 :)

The comment from @ToreAurstad can be spelled grep -Horn 'search' ./, which is easier to remember.

grep -HEroine 'search' ./ could also work ;)

For the curious:

$ grep --help | grep -Ee '-[HEroine],'
-E, --extended-regexp     PATTERNS are extended regular expressions
-e, --regexp=PATTERNS     use PATTERNS for matching
-i, --ignore-case         ignore case distinctions
-n, --line-number         print line number with output lines
-H, --with-filename       print file name with output lines
-o, --only-matching       show only nonempty parts of lines that match
-r, --recursive           like --directories=recurse

Here's how I used the upvoted answer to search a tree to find the fortran files containing a string:

find . -name "*.f" -exec grep -nHo the_string {} \;

Without the nHo, you learn only that some file, somewhere, matches the string.