Assorted shell and Python scripts
1#!/usr/bin/env bash
2
3# I shamefully used ChatGPT to generate this. My brain just is not suited to
4# coming up with that regex on my own and I didn't have much luck searching
5# the web for helpful material.
6
7# Function to convert a string to snake_case
8to_snake_case() {
9 local input="$1"
10 local snake_case
11 snake_case=$(echo "$input" | sed -E 's/[[:space:]]+/_/g; s/([a-z])([A-Z])/\1_\2/g; s/[^a-zA-Z0-9_]+/_/g; s/__+/_/g; s/^_+|_+$//g' | tr '[:upper:]' '[:lower:]')
12 echo "$snake_case"
13}
14
15# Check if the file name is provided as an argument
16if [ -z "$1" ]; then
17 echo "Usage: $0 <file-name>"
18 exit 1
19fi
20
21# Get the file name from the argument
22file_name="$1"
23
24# Extract the directory, base name, and extension
25dir=$(dirname "$file_name")
26base_name=$(basename "$file_name")
27extension="${base_name##*.}"
28base_name="${base_name%.*}"
29
30# Convert the base name to snake_case
31snake_case_base_name=$(to_snake_case "$base_name")
32
33# Construct the new file name
34if [ "$base_name" == "$extension" ]; then
35 new_file_name="$dir/$snake_case_base_name"
36else
37 new_file_name="$dir/$snake_case_base_name.$extension"
38fi
39
40# Rename the file
41mv "$file_name" "$new_file_name"
42
43echo "File renamed to: $new_file_name"