Useful BASH Script for Renaming Files in a Directory Lowercase and Removing Any Special Characters or Spaces
Useful BASH Script for Renaming Files in a Directory Lowercase and Removing Any Special Characters or Spaces
#!/bin/bash
for file in *; do # Skip if not a regular file [ -f “$file” ] || continue
# Extract base name and extension
base="${file%.*}"
ext="${file##*.}"
# Handle files without an extension
if [[ "$file" == "$base" ]]; then
new_base=$(echo "$base" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/_/g')
new_name="$new_base"
else
new_base=$(echo "$base" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]/_/g')
new_ext=$(echo "$ext" | tr '[:upper:]' '[:lower:]') # Normalise extension too
new_name="${new_base}.${new_ext}"
fi
# Rename only if the new name is different
if [[ "$file" != "$new_name" ]]; then
mv -n -- "$file" "$new_name"
fi done