Create a gist now

Instantly share code, notes, and snippets.

@bencrowder /dub.sh
Last active Dec 14, 2015

What would you like to do?
Batch file renaming for zsh.
#!/bin/zsh
# Batch rename
# Usage: dub image-X.jpg *.jpg
#
# - First argument is template for renaming
# - The "X" in the template will be replaced with zero-padded numbers
# (e.g., image-001.jpg, image-002.jpg, etc.)
#
# More examples:
# - dub pages.X.png *.PNG
# - dub book-X.jpg IMG_01*.JPG
# -------------------------------------------------------------------
# Get the list of files we're renaming
args=($*)
files=($args[2,-1])
# Figure out how many digits to use (based on # of files)
length=$files[(I)$files[-1]]
digits=${#length}
# Parse the rename template
template=$1
fileparts=(${(s/X/)template})
fileprefix=$fileparts[1]
filesuffix=$fileparts[2]
# Do the renaming
i=0; for x in $files; do ((++i)); mv $x $fileprefix${(l:${digits}::0:)i}$filesuffix; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment