Created
October 31, 2025 11:59
-
-
Save electerious/49a6030ca1fbceb42be45c555851c395 to your computer and use it in GitHub Desktop.
Script to rename files and directories in a git project to kebab-case
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Fail on any error | |
| set -euo pipefail | |
| folder="$1" | |
| if [[ -z "$folder" || ! -d "$folder" ]]; then | |
| echo "Usage: $0 <existing-folder>" | |
| exit 1 | |
| fi | |
| # Function to convert a filename to kebab case | |
| to_kebab_case() { | |
| local name="$1" | |
| # Add hyphens before uppercase letters (except at the beginning), | |
| # then convert to lowercase, replace spaces and underscores with hyphens, | |
| # remove special characters except dots (for file extensions), hyphens, and alphanumeric | |
| echo "$name" | \ | |
| sed 's/\([a-z0-9]\)\([A-Z]\)/\1-\2/g' | \ | |
| tr 'A-Z' 'a-z' | \ | |
| sed 's/[_ ]/-/g' | \ | |
| sed 's/[^a-z0-9.-]//g' | \ | |
| sed 's/--*/-/g' | \ | |
| sed 's/^-\|-$//g' | |
| } | |
| # Function to ask for user confirmation | |
| confirm_rename() { | |
| local current_name="$1" | |
| local new_name="$2" | |
| echo -n "Rename '$current_name' to '$new_name'? (Y/n): " | |
| read -r response | |
| # Default to yes if empty response or starts with Y/y | |
| if [[ -z "$response" || "$response" =~ ^[Yy] ]]; then | |
| return 0 | |
| else | |
| return 1 | |
| fi | |
| } | |
| # Function to rename files and directories to kebab case | |
| rename_to_kebab_case() { | |
| local dir="$1" | |
| # Collect all files and directories in an array, depth-first | |
| local -a files_to_process | |
| while IFS= read -r -d '' path; do | |
| files_to_process+=("$path") | |
| done < <(find "$dir" -depth -print0) | |
| # Process each file/directory | |
| for path in "${files_to_process[@]}"; do | |
| base=$(basename "$path") | |
| dirpath=$(dirname "$path") | |
| kebabbase=$(to_kebab_case "$base") | |
| if [[ "$base" != "$kebabbase" ]]; then | |
| target="$dirpath/$kebabbase" | |
| # Ask for user confirmation before renaming | |
| if confirm_rename "$base" "$kebabbase"; then | |
| # If target exists, rename original to a temp name first to avoid conflicts | |
| if [[ -e "$target" ]]; then | |
| tempname="$target.tmp_kebab_rename" | |
| git mv "$path" "$tempname" | |
| git mv "$tempname" "$target" | |
| echo "✓ Renamed '$base' to '$kebabbase'" | |
| else | |
| git mv "$path" "$target" | |
| echo "✓ Renamed '$base' to '$kebabbase'" | |
| fi | |
| else | |
| echo "✗ Skipped '$base'" | |
| fi | |
| fi | |
| done | |
| } | |
| rename_to_kebab_case "$folder" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment