Skip to content

Instantly share code, notes, and snippets.

@davehull
Created August 30, 2026 22:41
Show Gist options
  • Select an option

  • Save davehull/88afaf2c70b016bb702134b9dd99d993 to your computer and use it in GitHub Desktop.

Select an option

Save davehull/88afaf2c70b016bb702134b9dd99d993 to your computer and use it in GitHub Desktop.
Useful for renaming a bunch of files that include date stamps in their names
#!/bin/bash
# Default flag values
VERBOSE=false
WHAT_IF=false
# Parse flags and arguments
ARGS=()
while [[ $# -gt 0 ]]; do
case "$1" in
--verbose|-v)
VERBOSE=true
shift
;;
--whatif)
WHAT_IF=true
shift
;;
-*)
echo "Error: Unknown option $1" >&2
exit 1
;;
*)
ARGS+=("$1")
shift
;;
esac
done
# Ensure we have exactly two main arguments (old_date and new_date)
if [ ${#ARGS[@]} -ne 2 ]; then
echo "Usage: $(basename "$0") [--verbose] [--whatif] <old_date> <new_date>"
echo "Example: $(basename "$0") --whatif 260728 260619"
exit 1
fi
OLD_DATE="${ARGS[0]}"
NEW_DATE="${ARGS[1]}"
# Counter to track modified files
count=0
# Loop through all files in the current directory matching the OLD_DATE prefix
for file in "${OLD_DATE}"*; do
# Ensure the glob matched a real file
if [ ! -f "$file" ]; then
if [ "$count" -eq 0 ]; then
echo "No files found starting with '${OLD_DATE}'."
fi
break
fi
# Replace ONLY the leading OLD_DATE prefix with NEW_DATE
new_file="${NEW_DATE}${file#$OLD_DATE}"
# Perform rename (or simulate)
if [ "$WHAT_IF" = true ]; then
echo "[What If] Would rename: '$file' -> '$new_file'"
else
if [ "$VERBOSE" = true ]; then
echo "Renaming: '$file' -> '$new_file'"
fi
# -n prevents accidental overwrites if a file with new_file name exists
mv -n "$file" "$new_file"
fi
((count++))
done
if [ "$WHAT_IF" = true ]; then
echo "Done. Processed $count file(s) in preview mode."
elif [ "$VERBOSE" = true ]; then
echo "Done. Renamed $count file(s)."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment