← Back to all snippets
BASH

Recursively Find and Replace Text in Files

Implement a powerful bash command to recursively search and replace text strings across multiple files within a directory, perfect for batch code updates or configuration changes.

#!/bin/bash

# Configuration
SEARCH_DIR="./src"
OLD_TEXT="old_domain.com"
NEW_TEXT="new_domain.com"
FILE_EXTENSION="php" # e.g., php, js, html, txt. Use '*' for all files.

if [ -z "$OLD_TEXT" ] || [ -z "$NEW_TEXT" ]; then
  echo "Error: OLD_TEXT and NEW_TEXT cannot be empty."
  exit 1
fi

echo "Searching and replacing '${OLD_TEXT}' with '${NEW_TEXT}' in ${SEARCH_DIR}/*.${FILE_EXTENSION}"

# Use find to locate files and sed for in-place replacement
# The -i'' flag ensures compatibility across macOS (BSD sed) and Linux (GNU sed)
find "${SEARCH_DIR}" -type f -name "*.${FILE_EXTENSION}" -print0 | xargs -0 sed -i'' "s/${OLD_TEXT}/${NEW_TEXT}/g"

if [ $? -eq 0 ]; then
  echo "Replacement complete."
else
  echo "An error occurred during replacement."
  exit 1
fi
How it works: This bash script automates the process of finding and replacing text strings across multiple files within a specified directory. It uses `find` to recursively locate files matching a given extension and then pipes these file paths to `xargs`. `xargs` then executes `sed` for each file, performing an in-place (`-i`) global (`g`) substitution of `OLD_TEXT` with `NEW_TEXT`. This snippet is highly valuable for web developers to perform batch updates to codebases, such as changing domain names, API endpoints, or library versions across many files efficiently.

Need help integrating this into your project?

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

Hire DigitalCodeLabs