Last active
January 4, 2018 15:14
-
-
Save rbecheras/6ce05660c4796c003e79baddd5964de2 to your computer and use it in GitHub Desktop.
A script to rename in mass replacing a string by an other
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Bash colors | |
RED="\033[0;31m" | |
GREEN="\033[0;32m" | |
ORANGE="\033[0;33m" | |
YELLOW="\033[1;33m" | |
NC="\033[0m" # No Color | |
ERROR="${RED}ERREUR:" | |
SUCCESS="${GREEN}OK:" | |
WARNING="${ORANGE}ATTENTION:" | |
NOTICE="${YELLOW}INFO:" | |
if [[ -z "$1" ]] | |
then | |
printf "${ERROR} You must pass the source directory name as first argument${NC}\n" | |
exit 1 | |
fi | |
if [[ ! -d "$1" ]] | |
then | |
printf "${ERROR} The directory '$1' doesn't exist${NC}\n" | |
exit 1 | |
fi | |
if [[ -z "$2" ]] | |
then | |
printf "${ERROR} You must pass the search string as second argument${NC}\n" | |
exit 1 | |
fi | |
if [[ -z "$3" ]] | |
then | |
printf "${ERROR} You must pass the replace string as third argument${NC}\n" | |
exit 1 | |
fi | |
targetDir="${1%/}" | |
search="$2" | |
replace="$3" | |
printf "${NOTICE}> The process will rename the following files:${NC}\n" | |
for file in $(ls $targetDir) | |
do | |
newName="$(echo $file | sed s/$search/$replace/g)" | |
if [[ "$file" != "$newName" ]] | |
then | |
echo "* \"$file\" −−> \"$newName\" : mv $targetDir/$file $targetDir/$newName" | |
fi | |
done | |
printf "${NOTICE}\n> Do you confirm the process ?${NC}\n" | |
select yn in "Yes" "No"; do | |
case $yn in | |
Yes ) | |
start=`date +%s` | |
i=$((0)) | |
errorsNumber=$((0)) | |
for file in $(ls $targetDir) | |
do | |
newName="$(echo $file | sed s/$search/$replace/g)" | |
if [[ "$file" != "$newName" ]] | |
then | |
echo "* \"$file\" −−> \"$newName\"" | |
mv $targetDir/$file $targetDir/$newName | |
if [[ $? != "0" ]] | |
then | |
printf "${ERROR} Impossible de convertir '$file'${NC}\n" | |
errorsNumber=$(($errorsNumber+1)) | |
else | |
printf "${SUCCESS}.${NC}\n" | |
fi | |
fi | |
done | |
end=`date +%s` | |
runtime=$((end-start)) | |
if [[ $(($errorsNumber)) > 0 ]] | |
then | |
printf "${ERROR} $errorsNumber errors encountered!${NC}\n" | |
exit 1 | |
else | |
printf "${SUCCESS} $i files has been renamed in ${runtime}s.${NC}\n" | |
fi | |
break;; | |
No ) | |
printf "${WARNING} Process canceled by the user. Exiting.${NC}\n" | |
exit;; | |
esac | |
done | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Installation
Usage
In text mode :