BASH

Batch Find and Replace Text in Multiple Files

Learn how to efficiently find and replace specific text strings across multiple files within a directory using a simple Bash script, perfect for configuration updates or quick code refactoring.

#!/bin/bash

OLD_TEXT="$1"
NEW_TEXT="$2"
FILES_PATTERN="${3:-*.txt}" # Default to .txt files if not specified

if [ -z "$OLD_TEXT" ] || [ -z "$NEW_TEXT" ]; then
  echo "Usage: $0 <old_text> <new_text> [files_pattern]"
  exit 1
fi

echo "Replacing '$OLD_TEXT' with '$NEW_TEXT' in files matching '$FILES_PATTERN'..."

# Using 'sed -i' for in-place replacement. Make sure to back up if critical.
# For macOS/BSD sed, you might need 'sed -i '' "s/$OLD_TEXT/$NEW_TEXT/g"' 
find . -type f -name "$FILES_PATTERN" -print0 | while IFS= read -r -d $'\0' file; do
  echo "Processing $file..."
  # Use double quotes for variables in sed for proper expansion, but be careful with special chars
  # This simple version works for basic text. For complex patterns, escape $OLD_TEXT and $NEW_TEXT.
  sed -i "s/${OLD_TEXT//\//\\/}/${NEW_TEXT//\//\\/}/g" "$file"
done

echo "Replacement complete."
How it works: This Bash script automates finding and replacing text across multiple files. It takes the old text, new text, and an optional file pattern as arguments. It uses `find` to locate files matching the pattern and then pipes each file path to a `while read` loop. Inside the loop, `sed -i` performs an in-place global replacement of the old text with the new text. The script includes basic argument validation and handles special characters like forward slashes in the search/replace strings by escaping them for `sed`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs