Shell script to rename files from United States dates to international dates

I ended up with a lot of files named using US style dates ( month-day-year.txt ). These don’t sort nicely into chronological order so I wrote a small shell script to rename them. The files are changed from “month-day-year.txt” to “20year-month-day.txt”. The extension isn’t checked and is preserved so it works with any file extension. This does require a relatively modern version of Linux/Unix bash shell.

#!/bin/bash
regex=^[0-9]\{1,2\}-[0-9]\{1,2\}-[0-9]\{1,2\}\..*
for f in `ls *`
do
 if [[ $f =~ $regex ]]; then
 m=0`expr match "$f" '\(^[0-9]\{1,2\}\)'`
 m=${m:(-2)}
 d=0`expr match "$f" '.*-\([0-9]\{1,2\}\)-.*'`
 d=${d:(-2)}
 y=0`expr match "$f" '.*-\([0-9]\{1,2\}\)\..*'`
 y=${y:(-2)}
 e=`expr match "$f" '.*\.\(.*\)$'`

 echo $f "20$y-$m-$d.$e"
 mv $f "20$y-$m-$d.$e"
 fi
done

++djs

Leave a comment