Posted on under Tips by Owen Conti.
Here's a script you can use to automatically fix the file casings in a given directory. Let's say you have a directory like this:
1resources/2├── js/3│ ├── Components/4│ | ├── button.tsx
The script would fix it to be like so:
1resources/2├── js/3│ ├── components/4│ | ├── Button.tsx
Folder names become kebab-case and file names become PascalCase.
Usage:
1./fix-casings.sh folderName
1#!/bin/bash 2 3# Function to convert to kebab-case 4to_kebab_case() { 5 echo "$1" | sed -E 's/([a-z0-9])([A-Z])/\1-\2/g' | tr '[:upper:]' '[:lower:]' | tr ' ' '-' | tr '_' '-' 6} 7 8# Function to convert to PascalCase 9to_pascal_case() {10 filename=$111 # Split into name and extension12 name="${filename%.*}"13 extension="${filename##*.}"14 15 # If there's no extension, just process the name16 if [ "$name" = "$extension" ]; then17 echo "$name" | perl -pe 's/(^|[-_]|\s+)([a-z])/\U$2/g'18 else19 # Process name and reattach extension20 processed_name=$(echo "$name" | perl -pe 's/(^|[-_]|\s+)([a-z])/\U$2/g')21 echo "${processed_name}.${extension}"22 fi23}24 25DIR=$126 27# Get all files tracked by git28git ls-files "$DIR" | while read -r file; do29 dir=$(dirname "$file")30 filename=$(basename "$file")31 32 # Skip if it's in the .git directory33 if [[ "$dir" == .git* ]]; then34 continue35 fi36 37 # Convert directory path to kebab-case38 new_dir=$(echo "$dir" | tr '/' '\n' | while read -r part; do39 if [ "$part" != "." ]; then40 to_kebab_case "$part"41 else42 echo "."43 fi44 done | tr '\n' '/' | sed 's/\/$//')45 46 # Convert filename to PascalCase47 new_filename=$(to_pascal_case "$filename")48 49 # Construct new path50 new_path="${new_dir}/${new_filename}"51 52 # Only rename if there's a change53 if [ "$file" != "$new_path" ]; then54 # Use temporary name to avoid case-sensitivity issues55 temp_path="${new_dir}/temp_${RANDOM}_${new_filename}"56 git mv "$file" "$temp_path" 2>/dev/null57 git mv "$temp_path" "$new_path" 2>/dev/null58 echo "Renamed: $file → $new_path"59 fi60done
Hopefully you found this article useful! If you did, share it on X!
Found an issue with the article? Submit your edits against the repository.