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?

1

1 Answer 1

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
2
  • Should this work in Terminal? Please have a look at my question here.
    – geordie
    Jan 9, 2015 at 22:36
  • @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
    Jan 9, 2015 at 23:55

You must log in to answer this question.

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