• 4
name Punditsdkoslkdosdkoskdo

Batch rename directory with regex via command line on Linux

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



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})$3-$2-$1//' *

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

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


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/' *
  • 0
Reply Report

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--/'`
  echo $NEWNAME

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.

  • 0
Reply Report
for year in 20??; do
  pushd "$year"
  for file in *; do
    echo mv "$file" ../"Folder ${year} - ${file}"

Remove the echo if the output looks good to you.

  • 0
Reply Report