Batch rename directories with regex via command line on Linux

Solution 1:

Your regular expression is broken, I think you meant something like this:

's/(\d{2})-(\d{2})-(\d{2})/20$3-$2-$1/'

i.e. hyphens do not need escaping and the second slash was out of place.

Note that with this substitution you will also rename files with the new naming scheme. You probably want to anchor the regular expression. Something like this should work:

rename -n 's/^(\d{2})-(\d{2})-(\d{2})$/20$3-$2-$1/' *

Solution 2:

I would go the following route:

for i in `find . -name "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"`; do
  NEWNAME=`echo $i | sed 's/\([0-9][0-9]\)-\([0-9][0-9]\)-\([0-9][0-9]\)/20\3-\2-\1/'`
  echo $NEWNAME
done

Now, when you're satisfied with output, just replace "echo $NEWNAME" with "mv $i $NEWNAME".

Offcourse, this is not an error free solution, for example if there is a directory named 30-05-14 and 2014-05-30, this wouldn't rename the current dir but move it to 2014-05-30/. Since you said that you switched schemes at one point I suppose this won't happen (eg. you don't have dir for certain date in both formats).

Also this solution probably won't work if you have spaces in your directory names somewhere.