Skip to content

Instantly share code, notes, and snippets.

@bencrowder
Last active February 15, 2022 04:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bencrowder/5091048 to your computer and use it in GitHub Desktop.
Save bencrowder/5091048 to your computer and use it in GitHub Desktop.
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