Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Consider the following directory listing:

/a/1
/a/2
/a/3
/b/1
/b/2
/b/3/a
/b/3/b
/c/a.whatever
/c/b
/c/c

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

/a/1
/b/1
/b/3/a
/c/a.whatever

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

share|improve this question

3 Answers 3

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

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.

edit
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

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

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.