Script to rename and move music files

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
c.monty

Script to rename and move music files

Post by c.monty »

Hello!

I have organised the compilations in my music library with the following structure:
/music/<artist>_<album>/cd1
/music/<artist>_<album>/cd2

Every file in the directory has this naming convention:
<nn>_<title>.mp3
(e.g. 01_hereisthetitle.mp3)

The script should search for the compilations and identify them automatically.
Then, every file in directory cd1 should be renamed to 1-<nn>_<title>.mp3 (e.g. 1-01_hereisthetitle.mp3), and every file in directory cd2 should be renamed to 2-<nn>_<title>.mp3 (e.g. 2-01_hereisanothertitle.mp3).

Can you provide some input for the syntax of a bash script performing this task?

THX
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 1 time in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
User avatar
xenopeek
Level 25
Level 25
Posts: 29614
Joined: Wed Jul 06, 2011 3:58 am

Re: Script to rename and move music files

Post by xenopeek »

Bit different than your other request, but basically same approach just run the following command from the music directory. Assuming you don't have compilations with more than 9 CDs, this would work:

Code: Select all

for nr in 1 2 3 4 5 6 7 8 9; do find . -ipath "*/cd${nr}/*.mp3" -type f -printf "\"mv '%p' '%h/${nr}_%f'\"\n"; done | xargs -l bash -c
Again, just run the first part to get of list of the rename commands it would run:

Code: Select all

for nr in 1 2 3 4 5 6 7 8 9; do find . -ipath "*/cd${nr}/*.mp3" -type f -printf "\"mv '%p' '%h/${nr}_%f'\"\n"; done
This renames any mp3 file that is located in a directory called cd1 to cd9, and renames it as you shared. It leaves the mp3 file in the same directory. Did you mean you also wanted to move the files one directory up, so you don't need the cd1 to cd9 directories any more? Then run it as this command instead:

Code: Select all

for nr in 1 2 3 4 5 6 7 8 9; do find . -ipath "*/cd${nr}/*.mp3" -type f -printf "\"mv '%p' '%h/../${nr}_%f'\"\n"; done | xargs -l bash -c
There is probably a more elegant way to do this than with a for loop, but hey, it works :D
Image
Locked

Return to “Scripts & Bash”