Add to_snake_case

This commit is contained in:
Jeffrey Serio 2024-07-21 10:30:24 -05:00
parent 01f8853737
commit aa137cddd9
2 changed files with 43 additions and 12 deletions

12
snakify
View File

@ -1,12 +0,0 @@
#!/usr/bin/env zsh
# Snakify - convert file names to_snake_case
filename=$(basename -- "$1")
extension="${filename##*.}"
filename="${filename%.*}"
new_filename=$(echo ${filename// /_} | tr '-' '_' | tr -cd '[:alnum:]._-')
new_basename=$(echo "$new_filename.$extension")
mv -i "$1" "$new_basename"
if ! [ "$new_basename" = "${new_basename:l}" ]; then
mv -i "$new_basename" "${new_basename:l}"
fi

43
to_snake_case Executable file
View File

@ -0,0 +1,43 @@
#!/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"