Copy files and rename them by creation date

Solution 1:

If all your directories are in ~/foo, you can run this (assuming you want to rename everything that is in ~/foo):

cd ~/foo
for dir in *; do 
    t=`stat -c %y "$dir" | awk '{print $1"-"$2}' | 
       cut -d ":" -f 1,2 | sed 's/://'`
    mv "$dir" "$t"_"$dir";
done

For example:

$ ls -gG
total 20
drwxr-xr-x 2 4096 Jun 20 14:41 a
drwxr-xr-x 2 4096 Jun 21 14:40 b
drwxr-xr-x 2 4096 May 16 14:57 c
drwxr-xr-x 2 4096 Jun 21 14:33 d
drwxr-xr-x 2 4096 May  3 16:15 e
$ for dir in *; do 
    t=`stat -c %y "$dir" | awk '{print $1"-"$2}' | 
       cut -d ":" -f 1,2 | sed 's/://'`
    mv "$dir" "$t"_"$dir";
done
$ ls -gG
total 20
drwxr-xr-x 2 4096 May  3 16:15 2013-05-03-1615_e
drwxr-xr-x 2 4096 May 16 14:57 2013-05-16-1457_c
drwxr-xr-x 2 4096 Jun 20 14:41 2013-06-20-1441_a
drwxr-xr-x 2 4096 Jun 21 14:33 2013-06-21-1433_d
drwxr-xr-x 2 4096 Jun 21 14:40 2013-06-21-1440_b

The trick here is using stat to save the modification time in variable $t so we can use it as a name. If you want to preserve the modification dates of the directories and only change the name, do something like:

for dir in *; do 
    old=`mktemp` && touch -r "$dir" $old
    t=`stat -c %y "$dir" | awk '{print $1"-"$2}' | 
       cut -d ":" -f 1,2 | sed 's/://'`
    mv "$dir" "$t"_"$dir"; 
    touch -r $old "$t"_"$dir";
done