BASH

Perform Bulk Find and Replace Across Multiple Files

Efficiently update text in a large codebase using a Bash script with 'find' and 'sed' for bulk search and replace operations across multiple files.

#!/bin/bash

# Usage: ./replace_text.sh <directory> <old_text> <new_text>

DIRECTORY="$1"
OLD_TEXT="$2"
NEW_TEXT="$3"

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

echo "Searching for '$OLD_TEXT' and replacing with '$NEW_TEXT' in files under '$DIRECTORY'..."

# Use find to locate files (e.g., .js, .php, .css, .html) and sed for in-place replacement.
# The -i'' (or -i.bak for backup) is for in-place editing. On macOS, -i requires a backup extension (e.g., -i.bak).
# Use -i'' for no backup (macOS compatible). For Linux, just use -i.
find "$DIRECTORY" -type f \
  -name "*.js" -o -name "*.php" -o -name "*.css" -o -name "*.html" -o -name "*.json" | while read -r file; do
  # Check if file is writable
  if [ -w "$file" ]; then
    echo "Processing $file..."
    # Adjust -i for OS compatibility (Linux vs. macOS)
    # For Linux: sed -i "s/${OLD_TEXT}/${NEW_TEXT}/g" "$file"
    # For macOS: sed -i '' "s/${OLD_TEXT}/${NEW_TEXT}/g" "$file"
    sed -i '' "s/${OLD_TEXT}/${NEW_TEXT}/g" "$file"
  else
    echo "Skipping read-only file: $file"
  fi
done

echo "Replacement complete."
How it works: This script leverages the `find` command to locate specific file types (e.g., `.js`, `.php`, `.css`) within a given directory and then pipes the results to a `while read` loop. Inside the loop, `sed` performs an in-place global search and replace operation. It includes checks for missing arguments and file writability, making it a robust utility for refactoring, updating deprecated syntax, or making bulk content changes across your codebase.

Need help integrating this into your project?

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

Hire DigitalCodeLabs