0

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!

Community
  • 1
  • 1
Philipp
  • 27
  • 6
  • 2
    Better to make list in a file and read using `while` loop. Check [https://stackoverflow.com/questions/50886897/reading-file-in-while-loop-bash-scripting](https://stackoverflow.com/questions/50886897/reading-file-in-while-loop-bash-scripting) – Digvijay S May 16 '20 at 16:18

1 Answers1

1

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.

Kevin Cui
  • 766
  • 1
  • 6
  • 8