How do you get the first file in each subdirectory matching a list of file extensions? My goal is to run a program on just any one of the files in a series of subdirectories.

For example, below there are 3 subdirectories. I want to run the program on subdir1/file.dat, subdir2/file.d01 and subdir3/file1.dat given that I want to find files that have extension .dat or .d01.

subdir1 - file.dat, file.d01    
subdir2 - file.d01, file.d02, file.d03    
subdir3 - file1.dat, file2.dat

The following worked great for awhile, until I started to encounter directories like the last two. subdir3 is problematic, since all files end up getting processed.

find . -name "*.dat" -exec mixb {} \;

1 Answer 1


With zsh:

for d (subdir*(/)) mixb $d/*.(dat|d01)([1])

The bash equivalent would be something like:

shopt -s nullglob extglob
for d in subdir*/; do
  [ -L "${d%/}" ] && continue
  set -- "$d"*.@(dat|d01)
  [ "$#" -eq 0 ] || mixb "$1"
  • Thanks. Can something similar be done in bash?
    – jsheares
    Feb 13, 2015 at 0:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .