Super User is a question and answer site for computer enthusiasts and power users. 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

I wanted a list of files under a directory in name order to pass to an image viewer.

I am using find $PHOTODIR -iname "*.jpg". Unfortunately this produces the images out of order.

On a USB key (formatted FAT32) I could understand files are processed in the order of directory entries, so I copied to a Ext4 drive, which I thought would produce files in name order, but there are still problems; I guess they are in inode order.

ls lists in order, but I need relative paths.

Can anyone suggest a suitable script?

share|improve this question
up vote 9 down vote accepted

If by "name order" you mean a simple alphabetical sorting, you could just sort the find results, which works fine as long as the files do not contain a newline in their name:

find "$PHOTODIR" -iname "*.jpg" | sort

If you want to pass these as arguments to an image viewer—or any other command—you need to pipe them to xargs. This works out of the box as long as there's no whitespace in the file names or paths.

If you want this to work with any file name or path, use the -print0 argument to make find's output delimited by NUL-characters, sort with -z, and use xargs -0:

find "$PHOTODIR" -iname "*.jpg" -print0 | sort -z | xargs -0 <command>
share|improve this answer

You must log in to answer this question.

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