TheRepoClub-DotFiles/localbin/.local/bin/bulkrename
2022-01-22 14:46:14 +00:00

94 lines
2.5 KiB
Bash
Executable File

#!/usr/bin/env bash
# -*-coding:utf-8 -*-
# Auto updated?
# Yes
#File :
# bulkrename
#Author:
# The-Repo-Club [wayne6324@gmail.com]
#Github:
# https://github.com/The-Repo-Club/
#
# Created:
# Sun 31 October 2021, 05:16:39 PM [GMT]
# Modified:
# Fri 21 January 2022, 02:29:56 PM [GMT]
#
# Description:
# Run this script by setting it at: # Nemo -> Edit -> Preferences ->
# Behavior -> Bulk Rename # Select multiple files in Nemo and hit F2 (or
# right-click -> Rename)
#
# Return the index of the first ocurrence of a substring or -1 if none
# $1 = string
# $2 = substring
function strindex() {
x="${1%%$2*}"
[[ "$x" = "$1" ]] && echo -1 || echo "${#x}"
}
# Convert '+' to ' ' and '%20' to ' '
# $1 = string to decode
function urldecode() {
: "${*//+/ }"; echo -e "${_//%/\\x}";
}
# Log to temporary file if enabled
function log() {
echo $1 >> "/tmp/nemo-bulk-rename.log"
}
# Add index to string replacing placeholder if exists or at the end.
# $1 = string
# $2 = leadingCeroes
# $3 = index
function replaceCounter() {
if [[ "$counterIndex" -eq "-1" ]];
then
echo "$1_$3";
else
printf -v index "%0$2d" $3
echo ${1/"z:$2"/$index}
fi
}
log "============ New bulk rename at `date '+%Y-%m-%d %H:%M:%S'` ============"
fileName=$(yad --entry --title="Nemo - Bulk Rename" \
--window-icon="info" \
--text="Type new file name without extension ('/' is not allowed).\n\
Use z:# placeholder mask to specify counter position and amount of leading zeroes.\
\ni.e.:\n 'filename' = filename_1.ext (no mask)\n 'myz:2file' = my01file.ext (mask)")
if [[ -z "$fileName" ]]; then
exit 0
elif [[ $fileName == *\/* ]]; then
notify-send "Bulk Rename: Error" "Please insert a valid file name." -i error -u low
exit 1
fi
log "renaming files to: $fileName"
placeholder="z:"
counter=1
counterIndex=$(strindex "$fileName" "$placeholder")
leadingCeroes=${fileName:$counterIndex+2:1}
log "found placeholder at: $counterIndex for $leadingCeroes leading ceroes"
# loop throught files passed by Nemo
# paths come in the format "file:///home/user/.."
for i; do
i=$(urldecode $i)
# replace "file://" with ""
oldPath=${i/"file://"/""}
path="${oldPath%\/*}"
ext=${oldPath##*.}
newName="$path/$(replaceCounter "$fileName" "$leadingCeroes" "$counter").$ext"
log "renaming $oldPath to $newName"
mv "$oldPath" "$newName"
counter=$((counter+1))
done
counter=$((counter-1))
notify-send "Bulk Rename: Completed" "Renamed $counter files successfully" -i nemo -u low
exit 1