gpt4 book ai didi

仅 Grep 第一个匹配项并停止

转载 作者:行者123 更新时间:2023-12-02 10:35:50 25 4
gpt4 key购买 nike

我正在使用 grep 递归搜索目录,并使用以下参数希望只返回第一个匹配项。不幸的是,它返回了不止一个——事实上,我上次查看时返回了两个。似乎我有太多的争论,尤其是没有得到想要的结果。 :-/

# grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/directory

返回:

Pulsanti Operietur
Pulsanti Operietur

也许 grep 不是最好的方法?你告诉我,非常感谢。

最佳答案

-m 1 表示返回任何给定文件中的第一个匹配项。但它仍然会继续在其他文件中搜索。另外,如果同一行中有两个或多个匹配项,则将全部显示。

可以使用head -1来解决这个问题:

grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1

每个 grep 选项的解释:

-o, --only-matching, print only the matched part of the line (instead of the entire line)
-a, --text, process a binary file as if it were text
-m 1, --max-count, stop reading a file after 1 matching line
-h, --no-filename, suppress the prefixing of file names on output
-r, --recursive, read all files under a directory recursively

关于仅 Grep 第一个匹配项并停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14093452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com