Grep only the first match and stop

后端 未结 5 1956
误落风尘
误落风尘 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:28

    My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.

    0 讨论(0)
  • 2020-11-29 15:29

    You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.

    grep -m 1 -r "Not caching" * | head -1
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-29 15:33

    You can pipe grep result to head in conjunction with stdbuf.

    Note, that in order to ensure stopping after Nth match, you need to using stdbuf to make sure grep don't buffer its output:

    stdbuf -oL grep -rl 'pattern' * | head -n1
    stdbuf -oL grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -n1
    stdbuf -oL grep -nH -m 1 -R "django.conf.urls.defaults" * | head -n1
    

    As soon as head consumes 1 line, it terminated and grep will receive SIGPIPE because it still output something to pipe while head was gone.

    This assumed that no file names contain newline.

    0 讨论(0)
  • 2020-11-29 15:41

    A single liner, using find:

    find -type f -exec grep -lm1 "PATTERN" {} \; -a -quit
    
    0 讨论(0)
提交回复
热议问题