Skip to content

Instantly share code, notes, and snippets.

@henriquemoody
Last active October 1, 2015 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henriquemoody/1895544 to your computer and use it in GitHub Desktop.
Save henriquemoody/1895544 to your computer and use it in GitHub Desktop.
[rename-seq] Rename files in sequence
#!/usr/bin/env bash
# Usage: {script} [--debug|-d] DIRECTORY [ PREFIX ]
#
# --debug, -d Run script in debug mode
# --help, -h Displays this help
#
# Report bugs to Henrique Moody <henriquemoody@gmail.com>
#
declare DEBUG_MODE=0
_help()
{
sed -E 's/^#\s?(.*)/\1/g' "${0}" |
sed -nE '/^Usage/,/^Report/p' |
sed "s/{script}/$(basename "${0}")/g"
}
case "${1}" in
--debug | -d)
DEBUG_MODE=1
shift
;;
--help | -h)
_help
exit
;;
esac
if [[ -z "${1}" ]]; then
_help 1>&2
exit 1
fi
DIRECTORY="${1}"
if [ ! -d "${DIRECTORY}" ]; then
echo "$(basename "${0}"): \`${DIRECTORY}\` is not a valid directory." 1>&2
exit 2
else
cd "${DIRECTORY}"
fi
INDEX=1
if [ "${2}" ]; then
PREFIX="${2}"
else
PREFIX=$(basename "${PWD}")
fi
COUNT="$(ls -1 | wc -l | awk '{print $1}' | wc -c | awk '{print $1}')"
ls -1 |
sort |
while read old_name; do
number=$(printf "%0${COUNT}d" ${INDEX})
extension=$(echo "${old_name}" | sed -E 's/.+\.(.+)/\1/g' | tr '[A-Z]' '[a-z]')
new_name="${PREFIX}-${number}.${extension}"
if [ -f "${new_name}" ]; then
echo "File ${new_name} already exists" 1>&2
elif [[ ${DEBUG_MODE} -eq 1 ]]; then
echo "${old_name} -> ${new_name}"
else
mv -v "${old_name}" "${new_name}"
fi
let INDEX=${INDEX}+1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment