Ubuntu: Mass renaming directories to move the year from end to beginning


I am currently struggling with some music folders. I once decided to name them following the pattern: artist - album - year. I realized today that this wasn't a clever move and want now to name my directories following the pattern: year - artist - album as they will then show up in ascending order when listed.

I started doing the renaming by hand but, with roughly 700 folders, there has to be a simpler way ; I tried using gprename but I'm not so good at regex and bash scripting...

Is there anyone who could help me spare my poor fingertips ?

Some examples:

Aes Dana - Memory Shell - 2004   Anja Schneider & GummiHz - Back To Back (Remixes Part 2) - 2009  

would become

2004 - Aes Dana - Memory Shell  2009 - Anja Schneider & GummiHz - Back To Back (Remixes Part 2)  

EDIT: Some artist and album names have special characters like And.Id or Kool & The Gang. Though every directory has - as separator.


Assuming you have access to perl rename (generally available in Ubuntu - thanks to @Serg for clarifying the difference. If in doubt, call /usr/bin/rename and you should get the right one), you could use:

rename -n 's/(.*) - (\d{4})\//$2 - $1/' */  

Remove -n after testing to actually rename the directories. This assumes all the albums date between 1000 and 9999. Probably reasonable...


  • s/old/new replace old with new
  • (.*) save any number of any characters to reference as $1 later
  • (\d{4})\/ save four digits at the end of the line to reference as $2 later.
  • */ match all directories (not files - thanks to @muru for help!)


Simple Python script can do such job:

$ tree  .  â"œâ"€â"€ Aes Dana - Memory Shell - 2004  â"œâ"€â"€ Anja Schneider & GummiHz - Back To Back (Remixes Part 2) - 2009  â""â"€â"€ rename_dirs.py    2 directories, 1 file  $ ./rename_dirs.py */  $ tree  .  â"œâ"€â"€ 2004 - Aes Dana  -  Memory Shell   â"œâ"€â"€ 2009 - Anja Schneider & GummiHz  -  Back To Back (Remixes Part 2)   â""â"€â"€ rename_dirs.py  

Script contents:

#!/usr/bin/env python  from shutil import move;  import sys    for i in sys.argv[1:] :      parts = i[:-1].split('-')      year = parts[-1].strip()      new_name = year + " - " + " - ".join(parts[:-1]).strip()      move(i,new_name)  

How this works:

  • The main trick is that we execute script from the same directory where targets reside. We also pass */ to provide only directories as arguments to the script
  • The script iterates over all command-line arguments, breaking down each filename into list of strings at - character. New filename is constructed out of parts we extracted.
  • move() function from shutils module is what actually renames the directories

Note the usage: ./rename_dirs.py */

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »