Replace Text in Multiple Files with a Simple BASH Script

This is a problem that could come across quite often. How to replace text in multiple files at once?

If you are running a UNIX system you are lucky: with a simple BASH script you can achieve this.

How to Replace Text in Many Files with BASH scripting

There are several ways to achieve this, one of the easiest is using sed utility.

Assuming we need to change every “blue” occurrence to “red”, our replace_string.sh would look something like:

#!bin/bash
DIR="$1"
SEARCH="$2"
for f in $(find $DIR -name "$SEARCH" -type f); do
  cp $f $f.bak
  sed 's/blue/red/g' $f.bak > $f
done

And to run the script, simply specify the directory under which you would like to perform the search and what files to perform the action on as parameters:

./replace_string.sh /home/myusername/projects/myproject/ *.txt

This command will replace text in multiple files: in each .txt file under the path “/home/myusername/projects/myproject/”, every string “blue” will be replaced with the string “red” (and a backup file for each modified file will be created.

If you do not wish to keep a backup, add the following line after the sed command and before the “done” keyword, indicating the end of the for loop:

rm -f $f.bak
  • vikramaditya

    this is useful