0

我只想返回我用来搜索的术语的第一个实例(不区分大小写)(如果有匹配项),我该怎么做?

例子:

$ grep "exactly-this"

Binary file /Path/To/Some/Files/file.txt matches

我想返回如下结果:

$ grep "exactly-this"

exactly-this
4

2 回答 2

0

grep 有一个内置的计数参数

您可以使用该-m选项为 grep 提供计数参数

grep -m 1 "exactly-this"

如果要避免出现二进制文件的消息,请使用

grep -a -m 1 "exactly-this"

请注意,这将打印word发生匹配的位置。由于它是二进制文件,因此word可能跨越多行

于 2013-06-08T17:15:26.290 回答
0

您需要的-ogrep.

来自man page

 -o, --only-matching
             Prints only the matching part of the lines.

测试:

[jaypal:~/Temp] cat file
This is a file with some exactly this in the middle
with exactly this in the begining
and some at the very end in brackets (exactly this)

[jaypal:~/Temp] grep -o 'exactly this' file
exactly this
exactly this
exactly this

[jaypal:~/Temp] grep -om1 'exactly this' file
exactly this
于 2013-06-09T04:44:56.643 回答