Skip to content

Instantly share code, notes, and snippets.

@bugsysop
Created July 24, 2013 07:36
Show Gist options
  • Select an option

  • Save bugsysop/6068690 to your computer and use it in GitHub Desktop.

Select an option

Save bugsysop/6068690 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# Usage: {script} DIRECTORY [ PREFIX ]
#
# --help, h Displays this help
#
# Report bugs to Henrique Moody <[email protected]>
#
_help()
{
sed -E 's/^#\s?(.*)/\1/g' "${0}" |
sed -nE '/^Usage/,/^Report/p' |
sed "s/{script}/$(basename "${0}")/g"
}
if [ ${#} -eq 0 ]; then
_help 1>&2
exit 1
elif [[ "${1}" == '--help' ]] || [[ "${1}" == '-h' ]]; then
_help
exit
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 -1rt | 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
exit 3
fi
mv -v "${old_name}" "${new_name}"
let INDEX=${INDEX}+1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment