Skip to content

Instantly share code, notes, and snippets.

@zudsniper
Last active January 8, 2024 04:11
Show Gist options
  • Save zudsniper/4bb1596111018a3d086b6e031ba64c98 to your computer and use it in GitHub Desktop.
Save zudsniper/4bb1596111018a3d086b6e031ba64c98 to your computer and use it in GitHub Desktop.
remove disgusting spaces and other weird stuff from filenames

Clean Filenames

A bash script that replaces spaces, +, and certain invalid characters in filenames with underscores. It processes all files in a directory.

Installation

Run the following command to download and make the script executable:

curl -sSL "https://gist.zod.tf/4bb1596111018a3d086b6e031ba64c98/raw/cleanFilenames.sh" -o cleanFilenames.sh && chmod +x cleanFilenames.sh

Usage

The script takes one optional argument: the directory of files to rename. If no directory is specified, the script defaults to the current working directory.

./cleanFilenames.sh                # Rename files in the current directory
./cleanFilenames.sh /path/to/dir   # Rename files in /path/to/dir

For getting help:

./cleanFilenames.sh --help
./cleanFilenames.sh -h
#!/bin/bash
# v1.1.0
# written with old ass MacOS /bin/bash version in mind
# Check for help flags
if [[ "$#" -eq 1 && ( "$1" == "--help" || "$1" == "-h" ) ]]; then
echo "Usage: $0 [directory]"
echo ""
echo "Options:"
echo "-h, --help Show this help text"
echo ""
echo "CleanFilenames is a script that renames all files in a directory,"
echo "replacing spaces, +, and certain invalid characters with underscores."
echo "If no directory is passed as argument, it defaults to the current working directory."
echo ""
echo "Examples:"
echo "$0 Rename files in the current directory"
echo "$0 /path/to/directory Rename files in /path/to/directory"
exit
fi
# Set the starting directory either from argument 1 or use current directory
DIR="${1:-.}"
# Define a counter variable for keeping track of the renaming process
count=0
# Use find to iterate all files and directories
find "$DIR" -depth -print0 | while IFS= read -r -d '' file; do
# Replace spaces, whitespaces and questionably valid characters in filenames
dst=$(echo "$file" | sed 's/ /_/g; s/+/_/g; s/[=:\"*<>|?]\|[$'\t\r\n']/_/g')
# If the new path isn't the same as the old one, i.e. a change has been made
if [ "$dst" != "$file" ]; then
((count++))
# Move/rename the file or directory
mv -v "$file" "$dst" 2>/dev/null
echo -en "\rRenamed $count items... " # use carriage return to show updating total
fi
done
echo # print a newline
echo "Renaming completed. Total items renamed: $count"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment