Tag Archives: script

Regex file rename.

Short post today, trying to post more often.

Ever had a folder full of files?  Universally, the answer to that is yes.  But, have you ever wanted to mass rename the files according to a pattern?  I had such a need today.  I had a poorly thought out backup script for my sql files.  I had named them all by date in the pattern mm.dd.yy.tar.gz.  That works just fine for a year but after that, they don’t sort well.  You end up with something like below.

12.27.09.tar.gz
12.27.10.tar.gz
12.27.11.tar.gz
12.28.09.tar.gz
12.28.10.tar.gz
12.28.11.tar.gz

See the problem?  Its not sorted properly when you get a folder listing.  Makes it difficult to determine which backups you actually have.  So, I wrote a little regex to rename them all.  I matched the first four digits ($1) the last set of digits ($2) and the rest of the file ($3).  Then I rename it in the form 20$2.$1.$3.  This has the effect of placing the year at the beginning of the file like i should’ve done to begin with.

rename -v 's/(\d\d\.\d\d)\.(\d\d)\.(.+)$/20$2\.$1\.$3/' *.gz

That one little command instantly renamed 731 files saving me an enormous amount of time and effort.  Knowing regular expressions has been a very useful skill.  I strongly encourage anyone interested to visit regular-expressions.info.

References