mirror of
https://codeberg.org/hyperreal/bin
synced 2024-11-25 02:13:41 +01:00
Add to_snake_case
This commit is contained in:
parent
01f8853737
commit
aa137cddd9
12
snakify
12
snakify
@ -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
43
to_snake_case
Executable 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"
|
Loading…
Reference in New Issue
Block a user