Created
February 25, 2024 21:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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