Ask Ubuntu is a question and answer site for Ubuntu users and developers. 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

Consider the following directory listing:


I want a command that will find the first (alphanumeric sort) file in each directory (inc nested) and deliver the following output:


This seems like a job for find but I'm running low on coffee. Release the Ninjas!

share|improve this question

Another solution - should work with spaces in the paths

find . -type d -exec sh -c 'find "{}" -maxdepth 1 -type f | sort | head -n 1' ";"

On a side note, I discovered that ls lacks the options to output the full paths, and to list just files (not dirs) :(

share|improve this answer
I agree. At first I got stuck with ls, too. It sadly does not provide a usable output for this task. – cauon Oct 11 '12 at 13:38

Using the benefits of awk I came up with this:

find -type d | awk '{print "find "$0" -type f | head -1"}' | sh | uniq

uniq becomes necessary because find searches the subdirectories...probably could get around that with an additional find argument somehow.

version without uniq

find -type d | awk '{print "find "$0" -maxdepth 1 -type f | head -1"}' | sh

Note that you can easily adjust the number of printed files per directory. To sort the files beforehand use:

find -type d | awk '{print "find "$0" -maxdepth 1 -type f | sort | head -1"}' | sh
share|improve this answer

Well with a bit of poking, my own Ninja skills recuperated slightly and came up with this steamer:

find -type d | xargs -I{} bash -c "find {} -maxdepth 1 -type f | sort | head -1" | sort

Not the most elegant of filesystem queries but it outputs what I'd expect.

share|improve this answer
It is funny how all 3 answers at last finalize in calling a shell with literally the same input command :D – cauon Oct 11 '12 at 13:41

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.