Created
June 4, 2020 14:17
-
-
Save gokhansolak/3b5cee6fc0aefa565b011defc52d908d to your computer and use it in GitHub Desktop.
Re-index files by changing the index suffix of file names.
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
#!/bin/bash | |
# Re-index files by changing the index suffix of file names. | |
# Usage: reindex_files <pattern> <offset> | |
# It renames all files in the folder following "pattern + number + extension" naming. | |
# <pattern> can be any regex (care not to match the index number). | |
# <number> is an integer ([0-9]+) | |
# It works for files with no extension as well. | |
# It will ask for confirmation before renaming the files. | |
rename_all(){ | |
pattern=$1 | |
offset=$2 | |
apply=$3 | |
for filename in *; do | |
if [[ "$filename" =~ ^${pattern}.* ]]; then | |
extension=".${filename##*.}" | |
basename="${filename%.*}" | |
# no extension? | |
if [[ "$extension" == ".$basename" ]]; then | |
extension="" | |
fi | |
# get the index and prefix | |
[[ $basename =~ (^${pattern})([0-9]+) ]] | |
prefix=${BASH_REMATCH[1]} | |
old_index=${BASH_REMATCH[2]} | |
index=$((old_index + offset)) | |
echo "$filename > $prefix$index$extension" | |
if [[ $apply = "y" ]]; then | |
mv "$filename" "$prefix$index$extension" | |
fi | |
fi | |
done | |
} | |
if [ "$#" -ne "2" ]; then | |
echo "Usage: reindex_files <prefix> <offset>" | |
echo "prefix can be a regex expression" | |
exit 0 | |
fi | |
rename_all $1 $2 "n" | |
read -p "Above changes are ok? (y/n)" yn | |
# user consent | |
if [ "$yn" == "y" ]; then | |
rename_all $1 $2 "y" | |
echo "renamed files" | |
fi | |
echo "finished" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment