#! /bin/bash
phelp()
{
echo "$usage
All files that match oldpattern will be renamed with the
filename components that match the constant parts of oldpattern
changed to the corresponding constant parts of newpattern.
The components of the filename that match variable parts of
oldpattern will be preserved. Variable parts in oldpattern
must occur in the same order in newpattern. Variables parts
can be '?' and '*'.
Example:
rename \"/tmp/foo*.ba.?\" \"/tmp/new*x?\"
All files in /tmp that match foo*.ba.? will have the \"foo\" part
replaced by \"new\" and the \".ba.\" part replaced by \"x\"."
}
usage="usage: $name [-htv] oldpattern newpattern"
name=${0
while getopts "htv" opt; do
case "$opt" in
t) tell=true;;
v) verbose=true;;
h) phelp; exit 0;;
*) echo "$name: $usage" 1>&2; exit 2;;
esac
done
shift $((OPTIND - 1))
if [ $ phelp
exit 2
fi
oldpat=$1
newpat=$2
set -- $1
if [ ! -e "$1" ]; then
echo "$name: no files match $oldpat."
exit 1
fi
typeset -i i=1 j
while :; do
case "$oldpat" in
*[\*\?]*) ;;
*) break;;
esac
pat=${oldpat pat=${oldpat%%"$pat"} pat=${pat oldpre[i]=${oldpat%%"$pat"*} oldsuf[i]=${oldpat newpre[i]=${newpat%%"$pat"*} oldpat=${oldpat newpat=${newpat let i=i+1
done
if [ $i -eq 1 ]; then
echo "No globbing chars in pattern." 1>&2
exit 1
fi
oldpre[i]=${oldpat%%"$pat"*} oldsuf[i]=${oldpatnewpre[i]=${newpat%%"$pat"*}
if [ -n "$verbose" ]; then
j=1
while let "j < i"; do
echo \
"Old prefix: ${oldpre[j]} Old suffix: ${oldsuf[j]} New prefix: ${newpre[j]}"
let j=j+1
done
fi
for file; do
j=1
origname=$file newfile=
while let "j <= i"; do
file=${file const=${file%${oldsuf[j]}} newfile=$newfile${newpre[j]}$const file=${file let j=j+1
done
if [ -n "$tell" ]; then
echo "Would move \"$origname\" to \"$newfile\"."
else
if [ -n "$verbose" ]; then
echo "Moving \"$origname\" to \"$newfile\"."
fi
mv $origname $newfile
fi
done