How To Automate Text Replacement in Multiple Files Using Bash

How to Automate Text Replacement in Multiple Files Using Bash?

It takes a lot of effort and is capable of error to manually update out-of-date information across several files. Whether it’s modifying configuration values, renaming variables, or updating file paths, Bash provides powerful tools like grep, sed, and find to automate this process efficiently. In this guide, we’ll walk you through automating bulk text replacement in multiple files using a simple Bash script.

Read More: How to Transfer Files Between Windows and Linux Using WinSCP?

Why Automate Text Replacement?

Automating text replacement is useful for:

  • Updating variable names in code files.
  • Changing file paths in scripts.
  • Fixing incorrect configuration settings.
  • Renaming project names in the documentation.

Instead of manually editing each file, a Bash script can accomplish this task in seconds.

Practical Example: Bulk Replacing Paths in Multiple Files

Imagine you have multiple files referring to outdated log file paths:

Old Path: ~/data/logs/app.log

New Path: ~/data/log/app.log

Instead of manually searching and replacing each instance, let’s automate it using Bash.

Step 1: Create a Test Environment

Before modifying real files, it’s best to test on sample files. Follow these steps:

Create a directory and navigate to it:

mkdir -p ~/replace_test && cd ~/replace_test

Create sample files containing the old path:

echo 'Log file: ~/data/logs/app.log' > script1.sh
echo 'ERROR_LOG="~/data/logs/app.log"' > config.env
echo 'echo "Processing ~/data/logs/app.log"' > process.sh

Verify occurrences of the old path:

grep "~/data/logs/app.log" *

Step 2: Create a Bash Script for Text Replacement

Now, create a script named replace_text.sh with the following content:

#!/usr/bin/env bash

if [[ $# -ne 3 ]]; then
    echo "Usage: $0 <old_path> <new_path> <directory>"
    exit 1
fi

OLD_PATH=$(printf '%s\n' "$1" | sed 's/[\/&]/\\&/g')
NEW_PATH=$(printf '%s\n' "$2" | sed 's/[\/&]/\\&/g')
SEARCH_DIR=$3

echo "Replacing occurrences of: $1 -> $2 in $SEARCH_DIR"

# Find and replace text safely
find "$SEARCH_DIR" -type f -exec sed -i "s/$OLD_PATH/$NEW_PATH/g" {} +

echo "Replacement completed."

Step 3: Make the Script Executable

Grant execution permission:

chmod +x replace_text.sh

Step 4: Execute the Script

Run the script to replace all occurrences of ~/data/logs/app.log with ~/data/log/app.log:

./replace_text.sh "~/data/logs/app.log" "~/data/log/app.log" ~/replace_test

Sample Output:

Replacing occurrences of: ~/data/logs/app.log -> ~/data/log/app.log in /home/user/replace_test
Replacement completed.

Step 5: Verify the Changes

Check for the new path:

grep "~/data/log/app.log" *

Ensure no old paths remain:

grep "~/data/logs/app.log" *

If there’s no output, the replacement was successful.

Why is this Effective?

  • Handles Special Characters: Escapes /, &, and other symbols correctly.
  • Uses find -exec sed Instead of grep | xargs sed: Safer for handling filenames with spaces.
  • Efficient for Large Projects: Works across multiple files without excessive CPU usage.

Best Practices Before Running on Real Files

  • Backup Your Files: Always create a backup before making bulk changes.
  • Test on a Sample Directory: Run it on a test directory before modifying real files.
  • Dry Run with grep: Check affected files before making changes using:grep -rl "~/data/logs/app.log" ~/replace_test/
  • Manually Inspect Changes: Review some modified files after execution.

Automation is key in modern IT workflows, and with the right tools, businesses can streamline operations efficiently. This is where Techwrix comes in, offering B2B media services to help companies stay ahead with the latest automation techniques, cloud solutions, and enterprise IT strategies.

Read More : Building a Robust Digital Infrastructure: The Role of SASE in Today’s Networking Landscape

Conclusion

In this tutorial, we learned how to replace text in multiple files using a simple Bash script. Automating bulk text replacement helps prevent errors and saves time. Before running it on critical files, always test with backups and verify results.

For more insights into IT automation and business solutions, trust Techwrix, your go-to partner for technology innovation and growth!