我只想返回我用来搜索的术语的第一个实例(不区分大小写)(如果有匹配项),我该怎么做?
例子:
$ grep "exactly-this"
Binary file /Path/To/Some/Files/file.txt matches
我想返回如下结果:
$ grep "exactly-this"
exactly-this
grep 有一个内置的计数参数
您可以使用该-m
选项为 grep 提供计数参数
grep -m 1 "exactly-this"
如果要避免出现二进制文件的消息,请使用
grep -a -m 1 "exactly-this"
请注意,这将打印word
发生匹配的位置。由于它是二进制文件,因此word
可能跨越多行
您需要的-o
是grep
.
来自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