Last active
April 12, 2024 07:38
-
-
Save yeiichi/453dc6386912ae1e3d0e60f085d53c2f to your computer and use it in GitHub Desktop.
Rename files/directories in the current directory.
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 | |
# Rename files/directories in the current directory. | |
# Unlike bash, sh doesn't implement [[ operator. Thus, the extension is intentionally set to .bash. | |
# Help message | |
if [[ $1 == '' || $1 == '--help' || $2 == '' ]]; then | |
{ | |
echo 'usage: renamer \033[3mpattern repl\033[0m\n' | |
exit | |
} | |
fi | |
# Safeguard: | |
if [[ ${#1} -lt 3 ]]; then | |
{ | |
echo "The \033[3mpattern\033[0m \"$1\" is too short: An extremely short \033[3mpattern\033[0m may cause unexpected pattern matching and destroy the filenames.\n" | |
exit | |
} | |
fi | |
n=0 | |
for i in $(ls); do | |
sub=$(echo $i | sed s/$1/$2/g) | |
mv ${i} ${sub} | |
if [[ ${i} != ${sub} ]]; then | |
echo 'Renamed:' ${i} '->' ${sub} | |
fi | |
# Emergency brake, just in case. | |
if [[ $n -gt 1000 ]]; then | |
break | |
fi | |
n=$(($n+1)) | |
done | |
echo '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment