Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
1  
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
add comment

1 Answer

up vote 14 down vote accepted

You could pipe the output of find through head:

find . -name '*.txt' | head -3

share|improve this answer
1  
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
1  
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
15  
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
2  
To summarize, -n 3 is POSIX compatible, and therefore likely to be more portable. –  l0b0 Mar 19 '13 at 16:11
show 4 more comments

Your Answer

 
discard

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.