Skip to content

Instantly share code, notes, and snippets.

@mhluska
Created April 21, 2013 04:57
Show Gist options
  • Save mhluska/5428539 to your computer and use it in GitHub Desktop.
Save mhluska/5428539 to your computer and use it in GitHub Desktop.
Give all the files in a directory incremental file names based on creation date. Example: img_000.jpg, img_001.jpg, etc.
#!/bin/bash
set -e
NAME=$(basename ${0})
USAGE="Usage: ${NAME} source target [prefix]"
function error {
echo "${NAME}: ${1:-'Unknown Error'}" 1>&2
echo ${USAGE} 1>&2
exit 1
}
if [ "${#}" -lt 2 ]; then
error 'Not enough arguments.'
fi
SOURCE=$(basename "${1}")
TARGET=$(basename "${2}")
PREFIX=${3:-file}
if [ ! -d "${SOURCE}" ]; then
error "Not a valid directory: ${SOURCE}"
exit 1
fi
mkdir -p ${TARGET}
counter=0
files=$(ls -1Rrt ${SOURCE})
total=$(echo "${files}" | wc -l | bc)
total_radix=${#total}
indices=($(seq -f "%0${total_radix}g" 0 ${total}))
IFS='
'
for file in ${files}; do
filename=$(basename "$file")
# Get the lowercase extension.
extension="${filename##*.}"
extension=$(tr '[:upper:]' '[:lower:]' <<< ${extension})
index=${indices[${counter}]}
cp "${SOURCE}/${file}" "${TARGET}/${PREFIX}_${index}.${extension}"
counter=$(( counter + 1 ))
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment