Skip to content

Instantly share code, notes, and snippets.

@yeiichi
Last active April 12, 2024 07:38
Show Gist options
  • Save yeiichi/453dc6386912ae1e3d0e60f085d53c2f to your computer and use it in GitHub Desktop.
Save yeiichi/453dc6386912ae1e3d0e60f085d53c2f to your computer and use it in GitHub Desktop.
Rename files/directories in the current directory.
#!/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