Owen Conti

Script for Changing Casing of Files

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=$1
11 # Split into name and extension
12 name="${filename%.*}"
13 extension="${filename##*.}"
14 
15 # If there's no extension, just process the name
16 if [ "$name" = "$extension" ]; then
17 echo "$name" | perl -pe 's/(^|[-_]|\s+)([a-z])/\U$2/g'
18 else
19 # Process name and reattach extension
20 processed_name=$(echo "$name" | perl -pe 's/(^|[-_]|\s+)([a-z])/\U$2/g')
21 echo "${processed_name}.${extension}"
22 fi
23}
24 
25DIR=$1
26 
27# Get all files tracked by git
28git ls-files "$DIR" | while read -r file; do
29 dir=$(dirname "$file")
30 filename=$(basename "$file")
31 
32 # Skip if it's in the .git directory
33 if [[ "$dir" == .git* ]]; then
34 continue
35 fi
36 
37 # Convert directory path to kebab-case
38 new_dir=$(echo "$dir" | tr '/' '\n' | while read -r part; do
39 if [ "$part" != "." ]; then
40 to_kebab_case "$part"
41 else
42 echo "."
43 fi
44 done | tr '\n' '/' | sed 's/\/$//')
45 
46 # Convert filename to PascalCase
47 new_filename=$(to_pascal_case "$filename")
48 
49 # Construct new path
50 new_path="${new_dir}/${new_filename}"
51 
52 # Only rename if there's a change
53 if [ "$file" != "$new_path" ]; then
54 # Use temporary name to avoid case-sensitivity issues
55 temp_path="${new_dir}/temp_${RANDOM}_${new_filename}"
56 git mv "$file" "$temp_path" 2>/dev/null
57 git mv "$temp_path" "$new_path" 2>/dev/null
58 echo "Renamed: $file$new_path"
59 fi
60done

Thanks for reading this article!

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.