Linux – How to stop the find command after second match

findlinux

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.

Best Answer

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.

Related Question