#!/usr/bin/env bash # rename_prefix.sh [-n|--dry-run] [-v] PREFIX REPLACEMENT set -o errexit -o pipefail set -o nounset dry_run=0 verbose=0 # ---- Parse flags while [[ $# -gt 0 ]]; do case "$1" in -n|--dry-run) dry_run=1; shift ;; -v|--verbose) verbose=1; shift ;; --) shift; break ;; -*) echo "Unknown option: $1" >&2; exit 2 ;; *) break ;; esac done if [[ $# -lt 2 ]]; then echo "Usage: ${0##*/} [-n|--dry-run] [-v] PREFIX REPLACEMENT" >&2 exit 2 fi prefix=$1 replacement=$2 if [[ -z "$prefix" ]]; then echo "Refusing to run: PREFIX cannot be empty." >&2 exit 2 fi # Match files in current dir whose names start with $prefix # nullglob: if no matches, the glob expands to nothing (prevents literal) shopt -s nullglob # Include dotfiles if the prefix starts with a dot (like .env) # (Bash already matches dotfiles when the pattern itself starts with a dot.) # Handle spaces safely by quoting $f everywhere. for f in -- "$prefix"*; do [[ -e "$f" ]] || continue dir=$(dirname -- "$f") base=$(basename -- "$f") # Replace only if $prefix is at the START of the filename newbase="${base/#$prefix/$replacement}" newpath="$dir/$newbase" # Skip if nothing changes [[ "$f" == "$newpath" ]] && continue if (( dry_run )); then printf '[DRY-RUN] mv -- %q %q\n' "$f" "$newpath" else # -n: don't overwrite existing files accidentally # Add -v if requested if (( verbose )); then mv -vn -- "$f" "$newpath" else mv -n -- "$f" "$newpath" fi fi done