Tips and tricks
Bash Script that replaces all the filenames in a dir
It prompts for:
- Folder path
- Text to find
- Text to replace with
Then it renames all files in that folder by replacing the first occurrence of the given string in each filename.
#!/bin/bash
# Ask for the folder path
read -p "Enter the folder path: " folder
# Check if folder exists
if [ ! -d "$folder" ]; then
echo "Error: Folder does not exist."
exit 1
fi
# Ask for the string to find
read -p "Enter the text to find in filenames: " find_text
# Ask for the string to replace with
read -p "Enter the text to replace with: " replace_text
# Use find to get all files recursively
find "$folder" -type f | while read -r file; do
filename=$(basename "$file")
dirname=$(dirname "$file")
# Replace first occurrence only
new_filename="${filename/$find_text/$replace_text}"
# Rename if changed
if [ "$filename" != "$new_filename" ]; then
mv "$file" "$dirname/$new_filename"
echo "Renamed: $filename -> $new_filename"
fi
done
echo "Done."