views:

285

answers:

1

Hi,

I have a directory filled with files with random names. I'd like to be able to rename them 'file 1' 'file 2' etc based on chronological order, ie file creation date. I could be writing a short Python script but then I wouldn't learn anything. I was wondering if there's a clever 1 line command that can solve this. If anyone could point me in the right direction.

I'm using zsh.

Thanks!

+1  A: 

For zsh:

saveIFS="$IFS"; IFS=$'\0'; while read -A line; do mv "${line[2]}" "${line[1]%.*}.${line[2]}"; done < <(find -maxdepth 1 -type f -printf "%T+ %f\n"); IFS="$saveIFS"

For Bash (note the differences in the option to read and zero-based indexing instead of one-based):

saveIFS="$IFS"; IFS=$'\0'; while read -a line; do mv "${line[1]}" "${line[0]%.*}.${line[1]}"; done < <(find -maxdepth 1 -type f -printf "%T+\0%f\n"); IFS="$saveIFS"

These rename files by adding the modification date to the beginning of the original filename, which is retained to prevent name collisions.

A filename resulting from this might look like:

2009-12-15+11:08:52.original.txt

Because a null is used as the internal field separator (IFS), filenames with spaces should be preserved.

Dennis Williamson