Skip to content

Instantly share code, notes, and snippets.

@enjoylife
Created March 21, 2024 12:06
Show Gist options
  • Save enjoylife/b08fa6f5a0e4ebf2d25ffbd30dcc0346 to your computer and use it in GitHub Desktop.
Save enjoylife/b08fa6f5a0e4ebf2d25ffbd30dcc0346 to your computer and use it in GitHub Desktop.
Rename all files recursively (Git aware)
#!/bin/bash
# Get the substring to replace and the replacement string
read -p "Enter substring to replace: " old_string
read -p "Enter replacement string: " new_string
# Function to rename files recursively
rename_files () {
for filename in *; do
# Check if filename contains the old string
if [[ $filename == *$old_string* ]]; then
# Generate the new filename with replacement
new_filename="${filename//$old_string/$new_string}"
# Rename the file (use mv command)
# mv "$filename" "$new_filename"
# Try to stage the rename with git mv (may not always work)
if git mv -f "$filename" "$new_filename" 2>/dev/null; then
echo "Staged rename: $filename -> $new_filename"
else
echo "WARNING: Git failed to stage rename: $filename -> $new_filename"
echo "You may need to stage the rename manually."
fi
# Print confirmation message
echo "Renamed: $filename -> $new_filename"
fi
# Check if it's a directory (except .)
if [[ -d "$filename" ]] && [[ "$filename" != "." ]]; then
# Call the function recursively for subdirectories
pushd "$filename" > /dev/null
rename_files
popd > /dev/null
fi
done
}
# Call the function for the current directory
rename_files
echo "Renaming completed!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment