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

bashbatch-renamecommand linedirectoryregex

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.

Best Answer

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...

Explanation

  • 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!)