Skip to content

Instantly share code, notes, and snippets.

@huangsam
Last active December 24, 2015 13:38
Show Gist options
  • Save huangsam/6806084 to your computer and use it in GitHub Desktop.
Save huangsam/6806084 to your computer and use it in GitHub Desktop.
Change file extensions in a directory.
#!/bin/bash
<<COMMENT
Author: Samuel Huang
rename.sh: change file extensions in a directory
COMMENT
path="."
interact=false
recurse=false
if [ $# -eq 0 ] ; then
echo "Usage: $0 [OPTION]... [OLD] [NEW]"
echo "Try $0 -h for more information."
exit 1
fi
function usage() {
cat <<EOF
Usage: $0 [OPTION]... [OLD] [NEW]
-h: help
-i: interactive
-p: desired path
-r: recursive
EOF
}
# reading optional parameters
while getopts :hip:r opt ; do
case $opt in
h)
usage
exit 0
;;
i)
interact=true
read -p "Enter old extension: " OLD
read -p "Enter new extension: " NEW
read -p "Enter desired path: " path
read -p "Recursive (Y/N): " var
if [ "$var" == "Y" ] ; then
recurse=true
fi
;;
p)
path="$OPTARG"
;;
r)
recurse=true
;;
\?)
echo "Invalid option: -$OPTARG"
;;
:)
echo "Option -$OPTARG requires an argument."
exit 1
;;
esac
done
# remove optional parameters
shift $(($OPTIND - 1))
if ! $interact ; then
OLD="$1"
NEW="$2"
fi
if $recurse ; then
fls=`/bin/find $path -type f -name "*.$OLD"`
else
fls=`/bin/ls $path/*.$OLD`
fi
# heavy-lifting
for ofile in $fls ; do
nfile=${ofile%.$OLD}.$NEW
/bin/mv $ofile $nfile
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment