shell script to replace string

Shell Script to Replace Text in File

Often you may need to substitute text in one or more files on your system. It is advisable to use a shell script to automate the whole process and replace text quickly. In this article, we will look at how to create a shell script to replace text in file. We will use sed command in a shell script for string substitution. We will accept old string, new string and file to modified as command line arguments.

Shell Script to Replace Text in File

Here are the steps to create shell script to replace text in file.

1. Create Blank Shell script file

Open terminal and run the following command to create a blank shell script file.

$ sudo vi

2. Shell Script to Replace Text in File

Add the following lines to your shell script file.


sudo sed -i "s/$2/$3/" $1

Save and close the file.

In the above code, the first line specifies the shell environment. Next line is the sed command for string substitution. sed is a popular Linux command for string operations.

Please note the sed command carefully. We mention -i option to modify the content of our file. We use command line arguments for shell script $1, $2 and $3 for file path, old string and new string respectively. Also we use double quotes in s/$2/$3 otherwise sed will treat $2 and $3 as literal strings and not shell variables.

3. Make Shell Script Executable

Run the following command to make our shell script executable.

$ sudo chomod +x

4. Test Shell Script

Let us say you have the following file /home/data.txt

input is equal to one

Let us say you want to replace the string ‘input’ with ‘output’ then call the above shell script as shown below

$ sudo ./ /home/data.txt input output

The first command line argument is the file path whose string you want to replace. Second argument is the old string, and third argument is the new string. If you don’t provide full path of your file, then the shell script will look for the file in your present working directory. Now if you see the content of your file

$ sudo cat /home/data.txt
output is equal to one

That’s it. In this article, we have looked at how to write a simple shell script to replace all occurrences of string with another string. You may modify this script as per your requirement.

Also read:

NGINX Block File Extension
How to Deploy React App on NGINX
How to Monitor NGINX Log Files using Ngxtop
How to Install Tomcat With NGINX Proxy
How to Install OpenOffice in Ubuntu

Leave a Reply

Your email address will not be published. Required fields are marked *