diff --git a/snakify b/snakify deleted file mode 100755 index 05c3da8..0000000 --- a/snakify +++ /dev/null @@ -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 diff --git a/to_snake_case b/to_snake_case new file mode 100755 index 0000000..5ec7224 --- /dev/null +++ b/to_snake_case @@ -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 " + 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"