← Back to all snippets
BASH

Find and Replace String in Multiple Files Recursively

Recursively search and replace a specific string or pattern within the content of multiple files in a directory, perfect for refactoring or bulk updates.

#!/bin/bash

# --- Configuration ---
SEARCH_DIR="/path/to/your/project"
OLD_STRING="old_variable_name"
NEW_STRING="new_variable_name"
FILE_EXTENSIONS="php|js|html|css" # Pipe-separated list of extensions to target

# --- Script Logic ---

if [ ! -d "$SEARCH_DIR" ]; then
  echo "Error: Search directory '$SEARCH_DIR' not found." >&2
  exit 1
fi

echo "Searching for '$OLD_STRING' and replacing with '$NEW_STRING' in files under $SEARCH_DIR..."

# Use find to locate relevant files and xargs to pass them to sed
find "$SEARCH_DIR" -type f -regex ".*\.\($FILE_EXTENSIONS\)$" -print0 | \
xargs -0 sed -i "s/${OLD_STRING}/${NEW_STRING}/g"

if [ $? -eq 0 ]; then
  echo "Replacement complete. Please review changes as 'sed -i' modifies files in place."
else
  echo "An error occurred during string replacement." >&2
fi

echo "String replacement script finished."
How it works: This script allows you to perform a find-and-replace operation across multiple files recursively within a specified directory. It uses `find` to locate files matching defined extensions and then pipes their paths to `xargs`. `xargs` in turn passes these files to `sed -i`, which performs an in-place search and replace of the `OLD_STRING` with the `NEW_STRING`. This is incredibly powerful for refactoring variable names, updating configuration strings, or making other bulk text changes across a codebase.

Need help integrating this into your project?

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

Hire DigitalCodeLabs