4

I have a folder on the server that contains directories that are created daily and are named by date, like so:

07-06-14
08-06-14
09-06-14

etc.

At some point I decided that a preferred naming would be in the following format: 2014-06-07 And the new folders get created with that format. So now the folder contains both: directories in old format and the new one.

How do I batch-rename the directories in the old format to the new one?

I've tried this: rename -n 's/(\d{2})\-(\d{2})\-(\d{2})\20$3-$2-$1//' *

But it throws errors: Use of uninitialized value $2 in regexp compilation at (eval 1) line 1

0

2 Answers 2

7

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/' *
2
  • Thanks, this seemed to work first and produced the following output: 01-04-14 renamed as 2014-04-01 ... but when I checked them on ftp they all still had the old names. Any suggestions?
    – YemSalat
    Jun 15, 2014 at 19:36
  • 3
    @YemSalat: the -n option tells rename to do a dry-run, so you can see what changes will be made. Remove it to actually realize them.
    – Thor
    Jun 15, 2014 at 19:44
3

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .