mirror of
https://codeberg.org/hyperreal/bin
synced 2024-11-01 16:43:08 +01:00
44 lines
1.2 KiB
Bash
Executable File
44 lines
1.2 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
|
|
# I shamefully used ChatGPT to generate this. My brain just is not suited to
|
|
# coming up with that regex on my own and I didn't have much luck searching
|
|
# the web for helpful material.
|
|
|
|
# Function to convert a string to snake_case
|
|
to_snake_case() {
|
|
local input="$1"
|
|
local snake_case
|
|
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:]')
|
|
echo "$snake_case"
|
|
}
|
|
|
|
# Check if the file name is provided as an argument
|
|
if [ -z "$1" ]; then
|
|
echo "Usage: $0 <file-name>"
|
|
exit 1
|
|
fi
|
|
|
|
# Get the file name from the argument
|
|
file_name="$1"
|
|
|
|
# Extract the directory, base name, and extension
|
|
dir=$(dirname "$file_name")
|
|
base_name=$(basename "$file_name")
|
|
extension="${base_name##*.}"
|
|
base_name="${base_name%.*}"
|
|
|
|
# Convert the base name to snake_case
|
|
snake_case_base_name=$(to_snake_case "$base_name")
|
|
|
|
# Construct the new file name
|
|
if [ "$base_name" == "$extension" ]; then
|
|
new_file_name="$dir/$snake_case_base_name"
|
|
else
|
|
new_file_name="$dir/$snake_case_base_name.$extension"
|
|
fi
|
|
|
|
# Rename the file
|
|
mv "$file_name" "$new_file_name"
|
|
|
|
echo "File renamed to: $new_file_name"
|