Skip to content

Instantly share code, notes, and snippets.

@mkelley33
Created February 25, 2024 21:53
Show Gist options
  • Save mkelley33/eb1549dddb65672a0724c2a91bd873fc to your computer and use it in GitHub Desktop.
Save mkelley33/eb1549dddb65672a0724c2a91bd873fc to your computer and use it in GitHub Desktop.
zsh script to replace all spaces and special characters in a file name for all files in the directory with dashes and make all letters lowercase removing the last dash in the file name
#!/bin/zsh
# Iterate over files in the directory
for filename in *; do
# Check if the filename is a regular file
if [[ -f "$filename" ]]; then
# Extract filename and extension
base_filename=$(basename "$filename")
extension="${base_filename##*.}"
base_filename="${base_filename%.*}"
# Replace spaces and special characters with dashes, and convert to lowercase
new_base_filename=$(echo "$base_filename" | tr -s '[:space:]' '-' | tr -s '[:punct:]' '-' | tr '[:upper:]' '[:lower:]')
# Remove trailing dashes
new_base_filename=${new_base_filename%-}
# Combine new filename with extension
new_filename="${new_base_filename}.${extension}"
# Rename the file
mv "$filename" "$(dirname "$filename")/$new_filename"
echo "File '$filename' renamed to '$new_filename'"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment