Grep列表文件名和行号

tre*_*065 81 awk grep

嗨,我正在尝试使用grep搜索我的rails目录.我正在寻找一个特定的单词,我想grep打印出文件名和行号.有一个grep标志会为我做这个吗?我一直在尝试使用-n和-l的组合,但这些都是打印出没有数字的文件名,或者只是将大量文本转储到终端,这些文本无法轻易读取.

例如:

  grep -ln "search" *
Run Code Online (Sandbox Code Playgroud)

我需要将它管道输入awk吗?

小智 125

我认为-l限制太多,因为它抑制了输出-n.我建议-H(--with-filename):打印每个匹配的文件名.

grep -Hn "search" *
Run Code Online (Sandbox Code Playgroud)

如果输出太多,请尝试-o仅打印匹配的部分.

grep -nHo "search" * 
Run Code Online (Sandbox Code Playgroud)


小智 29

grep -rin searchstring * | cut -d: -f1-2
Run Code Online (Sandbox Code Playgroud)

这就是说,递归搜索(对于searchstring本例中的字符串),忽略大小写,并显示行号.该grep的输出将如下所示:

/path/to/result/file.name:100: Line in file where 'searchstring' is found.
Run Code Online (Sandbox Code Playgroud)

接下来,我们将结果传递给cut命令,使用冒号:作为字段分隔符并显示字段1到2.

当我不需要我经常使用的行号-f1(只是文件名和路径),然后将输出传递给uniq,所以我只看到每个文件名一次:

grep -ir searchstring * | cut -d: -f1 | uniq
Run Code Online (Sandbox Code Playgroud)


Pet*_*nee 14

我喜欢用:

grep -niro 'searchstring' <path>

但那只是因为我总是忘记其他方式,我不能忘记Robert de grep -niro由于某种原因:)

  • 刚刚为法国人意识到`-noir`也有效;) (6认同)

Ict*_*tus 8

@ToreAurstad 的评论可以拼写为grep -Horn 'search' ./,这样更容易记住。

grep -HEroine 'search' ./也可以工作;)

对于好奇的人:

$ 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
Run Code Online (Sandbox Code Playgroud)