Skip to content

Instantly share code, notes, and snippets.

@schollz
Created April 16, 2024 14:00
Show Gist options
  • Save schollz/f23d3738611172bf572c17b1dc9a2a3c to your computer and use it in GitHub Desktop.
Save schollz/f23d3738611172bf572c17b1dc9a2a3c to your computer and use it in GitHub Desktop.
#!/bin/bash
# Function to generate a random string of characters
generate_random_string() {
cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1
}
# Function to recursively rename files and directories
rename_files_and_dirs() {
local path="$1"
# Find all files and directories in the path, from deepest to shallowest
find "$path" -depth -type d -o -type f | while read -r filename; do
local dirpath=$(dirname "$filename")
local base=$(basename "$filename")
local newname=""
# Check if it is a file with an extension
if [[ "$base" == *.* ]]; then
local ext="${base##*.}"
newname="$(generate_random_string).$ext"
else
newname="$(generate_random_string)"
fi
# Ensure the new filename does not already exist
while [[ -e "$dirpath/$newname" ]]; do
newname="$(generate_random_string)"
if [[ "$base" == *.* ]]; then
newname="$newname.$ext"
fi
done
mv -n "$filename" "$dirpath/$newname"
done
}
# Start renaming from the specified directory or the current directory if none specified
TARGET_DIR=${1:-.}
rename_files_and_dirs "$TARGET_DIR"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment