BASH

Find and Replace Text Across Files

A powerful bash script utilizing `find` and `sed` to efficiently search for and replace text patterns across multiple files in a web project directory.

#!/bin/bash

# Script to find and replace text in multiple files recursively

SEARCH_DIR="./src" # Directory to start searching from
SEARCH_TERM="old_string"
REPLACE_TERM="new_string"
FILE_EXTENSION="php" # or "js", "html", "css", "*" for all files

echo "Searching for '$SEARCH_TERM' and replacing with '$REPLACE_TERM' in files with extension '$FILE_EXTENSION' under '$SEARCH_DIR'"

# Use find to locate files and sed to perform in-place replacement
# The -i option of sed means "in-place edit". Add a suffix like -i.bak for backup if needed (e.g., sed -i.bak)

find "$SEARCH_DIR" -type f -name "*.$FILE_EXTENSION" -print0 | while IFS= read -r -d $'\0' file;
do
  if grep -q "$SEARCH_TERM" "$file"; then
    echo "Processing file: $file"
    # For macOS/BSD sed, you might need 'sed -i ""' or 'sed -i .bak'
    # For GNU sed (Linux), 'sed -i' is sufficient
    sed -i "s/$SEARCH_TERM/$REPLACE_TERM/g" "$file"
    if [ $? -eq 0 ]; then
      echo "Replaced in $file"
    else
      echo "Error replacing in $file"
    fi
  # else
  #   echo "Term not found in $file, skipping."
  fi
done

echo "Find and replace process completed."
How it works: This bash script leverages `find` and `sed` to recursively locate files and perform a global find-and-replace operation. It specifies a starting directory, a search term, a replacement term, and a file extension to target. The script iterates through matching files, checks if the search term exists using `grep`, and then uses `sed -i` to perform an in-place replacement. This is highly useful for refactoring code, updating configuration values, or migrating content across a web project, offering a powerful command-line utility for developers.

Need help integrating this into your project?

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

Hire DigitalCodeLabs