4

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.

αғsнιη
  • 41,407
  • 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. – αғsнιη Nov 08 '17 at 17:16
  • In particular nothing wrong without an explanatory comment. –  Nov 08 '17 at 17:19

2 Answers2

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.

Wildcard
  • 36,499
Ipor Sircer
  • 14,546
  • 1
  • 27
  • 39
0

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' _ {} +
αғsнιη
  • 41,407
  • 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 08 '17 at 22:32