Copy files and rename them by creation date

2

i have a few directories (1 level) that were added to my server in specific times. the problem is, they are named as a random hash.

would it be possible to copy them somewhere and rename by the original directory creation date in the process?

user1916182

Posted 2013-06-21T07:27:13.457

Reputation: 131

see if this gets you somewhere: http://stackoverflow.com/questions/4710753/rename-files-according-to-date-created

– TheUser1024 – 2013-06-21T09:00:16.407

Answers

2

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

terdon

Posted 2013-06-21T07:27:13.457

Reputation: 45 216

Should this work in Terminal? Please have a look at my question here.

– geordie – 2015-01-09T22:36:51.817

@geordie no, some of the options here won't be available on OSX. It's very late in my time zone but I'll try to give you an answer tomorrow. – terdon – 2015-01-09T23:55:58.200