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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: