Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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/' *
share|improve this answer
    
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 at 19:36
1  
@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 at 19:44
    
Apologize my ignorance, I'm very new to Linux. /Accepted answer/ –  YemSalat Jun 15 at 19:47
    
@YemSalat: no worries. –  Thor Jun 15 at 20:34

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.