BASH

Find and Replace String in Multiple Files

Safely find and replace a specific string across multiple files within a directory, with an optional backup, using `find` and `sed` commands for web project refactoring.

#!/bin/bash

# Usage: ./replace_string.sh "old_string" "new_string" "./src" ".js,.html"
# Backs up original files with .bak extension.

OLD_STRING="$1"
NEW_STRING="$2"
TARGET_DIR="${3:-.}" # Default to current directory
FILE_EXTENSIONS="${4:-.php,.html,.js,.css}" # Comma-separated list

if [ -z "$OLD_STRING" ] || [ -z "$NEW_STRING" ]; then
    echo "Usage: $0 <old_string> <new_string> [target_directory] [file_extensions]"
    echo "Example: $0 'http://old.cdn.com' 'https://new.cdn.com' './public' '.js,.css,.html'"
    exit 1
fi

echo "Searching in '$TARGET_DIR' for files with extensions: '$FILE_EXTENSIONS'"
echo "Replacing '$OLD_STRING' with '$NEW_STRING'"

# Convert comma-separated extensions to a find-compatible regex pattern
FIND_PATTERN=$(echo "$FILE_EXTENSIONS" | sed 's/,/ -o -name \*/g' | sed 's/^/\(/ -name \*/' | sed 's/$/\)/')

# Find files and perform replacement using sed -i for in-place edit with backup
# Check if GNU sed or BSD sed is in use
if sed --version 2>/dev/null | grep -q "GNU"; then
    FIND_CMD="find \"$TARGET_DIR\" -type f $FIND_PATTERN -print0 | xargs -0 sed -i.bak \"s/${OLD_STRING}/${NEW_STRING}/g\""
else
    # For BSD sed (macOS)
    FIND_CMD="find \"$TARGET_DIR\" -type f $FIND_PATTERN -print0 | xargs -0 sed -i '.bak' \"s/${OLD_STRING}/${NEW_STRING}/g\""
fi

echo "Executing: $FIND_CMD"
eval "$FIND_CMD"

echo "Replacement complete. Backup files created with .bak extension."
How it works: This script automates finding and replacing text strings across multiple files in a specified directory, which is a common task during refactoring or migration. It takes the old string, new string, target directory, and optional file extensions. It uses `find` to locate relevant files and `sed -i.bak` to perform an in-place replacement while creating a backup of the original files, ensuring safety. It also handles the subtle difference between GNU and BSD `sed` for wider compatibility.

Need help integrating this into your project?

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

Hire DigitalCodeLabs