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 {} \;

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 '15 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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