Calamity Jane
Calamity Jane

Reputation: 2676

Batch renaming files and directories with bash

I have several folders with mp3 files organised by genre, artist and album. I want to have the genres in capital letters, but everything below in the hierarchy with lowercase letters and devoid of special characters and whitespaces.

For this I have written a bash script, which accepts the path to the folder within all subfolders and files should be renamed:

#!/bin/bash

#Aufruf:
#$ ./alles.klein '/home/anja/Musik/HOERSPIELE' 

PFAD=$1

cd $PFAD

depthVarations=("-maxdepth 1 -type d" "-depth -type d" "-depth -type f") 

for i in "${depthVarations[@]}"
do
    :
    date
    echo $i
    find  .  $i -exec rename 'y/A-Z/a-z/' {} \;
    
    date
    echo $i
    find  .  $i -exec rename 's/(.*)(\.\/)(.*)/$1\/\L$3/' {} \;
    
    #.... several more regex variations
done

My problem is that it tries to change the whole path and not just the part I want to have changed e.g.

/home/anja/Musik/ORIENTALISCHES/A-wa 

becomes now

/home/anja/musik/orientalisches/a-wa  #everything is lowercase

the desired result would be:

/home/anja/Musik/ORIENTALISCHES/a-wa

As you see musik/orientalisches is changed to lowercase, too. I hoped that by "cd" into the right folder I might get only the path below, but it doesn't seem to work that way.

Upvotes: 1

Views: 115

Answers (1)

anubhava
anubhava

Reputation: 785146

You may use -execdir instead of -exec to lowercase only filename:

find . "$i" -execdir rename -n 'y/A-Z/a-z/' {} \;

Or else you may use this rename command:

find . "$i" -exec rename 's~^(.*/)(.+)~$1\L$2~' {} \;

or

find . "$i" -execdir rename 's~(.+)~\L$1~' {} \;

Upvotes: 1

Related Questions