Grep only the first match and stop

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

提交回复
热议问题