Philipp
Philipp

Reputation: 62

Find and rename directories on the basis of specific characters

My directory tree looks like this:

../files/Italy.Pictures.Tom.Canon.2017-April/
../files/Italy.Videos.Marie.Sony.2017-April/
../files/Spain.Pictures.Food.John.iPhone.2018-September/

and so on..

My code:

#!/bin/bash
DIR="/home/user/files/"
find $DIR -depth -name "* *" -execdir rename 's/ /./g' "{}" \; # replace space with dot
find $DIR -depth -iname "*.iphone*" -execdir rename 's/.iphone//ig' "{}" \; # remove 'iPhone' from dir name
find $DIR -depth -iname "*.john*" -execdir rename 's/.john//ig' "{}" \;
find $DIR -depth -iname "*.tom*" -execdir rename 's/.tom//ig' "{}" \;
find $DIR -depth -iname "*-april*" -execdir rename 's/-april//ig' "{}" \;
find $DIR -depth -iname "*-september*" -execdir rename 's/-september//ig' "{}" \;

and more commands like this for all names, month,..

Yes, this works!

But: Is this the best way to remove/replace characters in directory names? Any suggestions to make my script more efficient? Maybe, to put all words in a list, which should be removed?

Thanks for your thoughts!

Upvotes: 0

Views: 139

Answers (1)

Kevin Cui
Kevin Cui

Reputation: 846

Personally, I'd prefer using for loop with sed and mv to rename directories, instead of using find and rename. For example:

#!/usr/bin/env bash
for dir in $(ls -d ./*/); do
    newdir=$(sed 's/-.*$//' <<< "$dir" | sed 's/.\(iphone\|tom\|john\)//gi')
    mv "$dir" "$newdir"
done

The first sed is to remove the month name. The 2nd sed will remove all names, and it can be extended by adding other names.

I don't know if it's "the best" way to do the job. However, I find it's quite efficient and easy to maintain. Hope you would like this method as well.

Upvotes: 1

Related Questions