Grep only the first match and stop

后端 未结 5 1958
误落风尘
误落风尘 2020-11-29 15:14

I\'m searching a directory recursively using grep with the following arguments hoping to only return the first match. Unfortunately, it returns more than one -- in-fact two

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-29 15:31

    -m 1 means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.

    You can use head -1 to solve this problem:

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

    explanation of each grep option:

    -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
    

提交回复
热议问题