Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say there may be hundreds of *.txt files in a directory. I only want to find the first three *.txt files and then exit the searching process.

How to achieve this using the find utility? I had a quick through on its man page, seemed not such a option for this.

share|improve this question
You can use find . -name '*.txt' -print -quit only show the first match and let find exit after the first match. I do not know if it is possible to adapt to the case "exit after finding n matches". – N.N. Mar 19 '13 at 9:49
up vote 19 down vote accepted

You could pipe the output of find through head:

find . -name '*.txt' | head -n 3
share|improve this answer
I knew this, I want exit the searching process after finding out the first three matched files. There can be huge amount of matched files I don't care. – mitnk Mar 19 '13 at 8:31
I think the find command does get terminated once head has printed the first 3 files – Chris Card Mar 19 '13 at 8:48
Yes, it's strange, but you are right. – mitnk Mar 19 '13 at 9:22
It's not at all strange - it's how pipes work in UNIX. head starts up and waits for input from the lefthand side of the pipe. Then find starts up and searches for files that match the criteria specified, sending its output through the pipe. When head has received and printed the number of lines requested, it terminates, closing the pipe. find notices the closed pipe and it also terminates. Simple, elegant and efficient. – D_Bye Mar 19 '13 at 9:37
To summarize, -n 3 is POSIX compatible, and therefore likely to be more portable. – l0b0 Mar 19 '13 at 16:11

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.