How to make find command, that will show only first two matches and then end, something similiar to How to stop the find command after first match? just version for two records.

  • 1
    I think nothing is wrong with this question to get down-vote (at least in my opinion), if no, please leave comment where it's wrong question. Nov 8, 2017 at 17:16
  • In particular nothing wrong without an explanatory comment.
    – user147505
    Nov 8, 2017 at 17:19

2 Answers 2


Replace 1 to 2 in your linked answer.

find . ... -print | head -n 2

Note that this does assume that the filenames are sane, i.e. they do not contain newlines. Therefore it is not the most appropriate for a scripted solution. (See Why is looping over find's output bad practice? for more details.) It's still by far the most suitable approach for quick interactive use.

Also note that on a system with a great many files, this will be faster than a -exec sh -c 'echo "$1"; echo "$2"' _ {} + approach, because the find process will receive SIGPIPE when it tries to write more filenames after head has completed, and then find will end.

Not to mention that the -exec command may print a LOT more than 2 results if there are sufficiently many results. For example, find / -exec sh -c 'echo "$1"; echo "$2"' _ {} + will not exit for a very long time, and will print two files out of every ARG_MAX results rather than two files total.

  • And is there any option, to pick only second reasult from this query? Nov 8, 2017 at 16:19
  • 1
    Several ways. find [...] | head -n2 | tail -n1; find [...] | sed -n '2p'; find [...] | awk 'NR==2 { print }', amongst myriad others.
    – DopeGhoti
    Nov 8, 2017 at 16:22

Using find with invoking sh:

find . -type f -exec sh -c 'echo "$1" "$2"; done' _ {} +

This will expand all files since of using + terminator of -exec then we are just printing first and second arguments which are first and second files find found.

Or use as following which where you can specify after how many files found (maybe not 2 files, 100 files! then at above you should specify all 100 files!) exit the command (actually shell send exit command and cause find exit its running process).

find -type f -exec sh -c '
    for file; do echo "$file"; c=$((c+1)); [ $c = 2 ] && exit; done' _ {} +
  • 1
    Note that if there are HUGE numbers of results (in excess of ARG_MAX for the system), this command may also operate on another file besides the one intended.
    – Wildcard
    Nov 8, 2017 at 22:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .