#!/bin/bash
# /usr/local/bin/rename.sh
# http://crystalfaeries.net/posix/bin/rename.sh
# not originally by, but adopted by:
# celeste:crystalfaery 2015-04-19 08:38:38+00:00
# Original author and license unknown... Please
# notify kahealani@inbox.com if you know its source!
# Usage:
# rename PATTERN NEWNAME
#
# e.g.:
# rename IMG_11 iphone-screen-pic-
renumber=0; fixpng=1; doit=1; count=1
args=$(getopt npt $*)
if [ $? != 0 -o $# -lt 2 ] ; then
echo "Usage: $(basename $0) {-p} {-n} {-t} PATTERN NEWPATTERN"
echo "
echo " -p rewrites PNG to png"
echo " -n sequentially numbers matching files with"
echo " NEWPATTERN as base filename"
echo " -t test mode: show what you’ll do, don’t do it."
exit 0
fi
set -- $args
for i; do
case "$i"
in
-n ) renumber=1 ; shift ;;
-p ) fixpng=1 ; shift ;;
-t ) doit=0 ; shift ;;
-- ) shift; break ;;
fi
matches="$(ls -1 $1* 2>&1 | grep -v "No such file" | wc -l)"
if [ $doit -eq 0 ] ; then
echo "Debug: renumber = $renumber, fixpng = $fixpng, doit = $doit, matches = $matches"
fi
if [ $matches -eq 0 ] ; then
echo "Error: no files match pattern $1*"
exit 0
fi
for name in $1*
do
new="$(echo $name | sed "s/$1/$2/")"
if [ $fixpng -eq 1 ] ; then
new="$(echo $new | sed 's/PNG$/png/')"
fi
if [ $renumber -eq 1 ] ; then # with renumbering, we discard original filename
# the following assumes that we only have a single dot in the filename !!
suffix="$(echo $name | cut -d. -f2- | tr '[A-Z]' '[a-z]')"
new="$2$count.$suffix"
count=$(( $count + 1 ))
echo "mv $name $new"
if [ $doit -eq 1 ] ; then
mv $name $new ; chmod a+r $new
fi
else
echo "mv $name $new"
if [ $doit -eq 1 ] ; then
mv $name $new ; chmod a+r $new
fi
fi
done
exit 0
syntax highlighted by Code2HTML, v. 0.9.1