Home

Geeklog: What I Learnt Today / Adam

Renaming files based on their modification date in bash

> I wanted to rename all my photos to their modification dates cause Ikeep moving them from machine to machine OS to OS and losing the date info. It turned out to be a bit awkward but this works on Mac OSX

#!/bin/sh
## 
# copies all files in folder to YYYYMMDD.extension from their modification time; 
#
# @param folder		where to look for files in and where the renamed files will end up
#
# @return 			renamed files in folder
folder="test/" counter=0; for i in $folder* do counter=$[counter+1];
mon="" j=`stat -f %Sm "$i" | awk '{printf("%d-%s-%02d",$4,$1,$2)}'` #echo "$j"; ext=`echo ${i:(-4)} | tr '[:upper:]' '[:lower:]'`; #echo $ext; case `echo ${j:5:3}` in Jan) mon=01 ;; Feb) mon=02 ;; Mar) mon=03 ;; Apr) mon=04 ;; May) mon=05 ;; Jun) mon=06 ;; Jul) mon=07 ;; Aug) mon=08 ;; Sep) mon=09 ;; Oct) mon=10 ;; Nov) mon=11 ;; Dec) mon=12 ;; *) mon=ERR esac j=${j:0:4}$mon${j:9:2} echo "$i ->" $folder$j$ext; mv "$i" $folder$j$ext; done echo $counter" files in \""$folder"\" renamed";

/ Adam