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.

- 41,407

- 313
-
1I 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. – αғsнιη Nov 08 '17 at 17:16
-
In particular nothing wrong without an explanatory comment. – Nov 08 '17 at 17:19
2 Answers
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.

- 36,499

- 14,546
- 1
- 27
- 39
-
And is there any option, to pick only second reasult from this query? – harcotlupus Nov 08 '17 at 16:19
-
1Several ways.
find [...] | head -n2 | tail -n1
;find [...] | sed -n '2p'
;find [...] | awk 'NR==2 { print }'
, amongst myriad others. – DopeGhoti Nov 08 '17 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' _ {} +

- 41,407
-
1Note 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 08 '17 at 22:32