24 March 2006

sorting files by modification date

At times I've found that I need to sort the contents of a directory by modification date. If all the files are in a single directory, 'ls -lt' will do the trick. But it's not so easy if the files are scattered through an arbitrarily complicated directory structure. So I've saved the following shell script in ~/bin/file_epoch.sh (and made it executable w/ 'chmod 700 ~/bin/file_epoch.sh'):

mod_time="`/bin/ls --full-time \"${file_name}\" \
| awk '{ print $6,$7; }' | cut -d'.' -f1`"
epoch="`date -d \"${mod_time}\" +%Y%m%d%H%M%S`"
echo "${epoch} ${file_name}"

The script takes a single filename as its argument, and the output is something like this:

20060324152639 /path/to/some/file

Then when I need to sort the files, I just do this:

find /path/to/directory/structure -type f \
-exec ~/bin/file_epoch.sh {} \; | sort -rn

This runs the script on every file in /path/to/directory/structure, and piping the output to 'sort -rn' sorts the files in chronological order (from newest to oldest).

No comments: