Skip to content
Related Articles

Related Articles

Improve Article

Shell Script to Perform String Replacement in a File

  • Last Updated : 29 Jun, 2021

String replacement is the process of replacing a string with another in a particular block of code, text, or the entire file. There are instances where we need to replace one string with another, but there are a lot of instances of such strings. There are two solutions here; you can manually replace all the strings one by one or write some commands to replace one string with another all at once. The latter solution reduces the efforts and saves time, and also gives exposure to some Linux commands and utilities.

Approach

The approach to string replacement in a file is quite simple and straightforward. We need to input the file name, the existing string, and the new string to be substituted by the user. We can replace the string in the entire file or a specific part mentioned by start and end lines. So, for that, we’ll need an if-else condition for checking for the entire file string replacement or a specific part. We’ll be making use of the sed command to make the actual replacement. Finally, printing the changes in the file.

Explanation

We need to solve the problem in chunks. First of all, the user input for the substituted strings and then the choice of a replacement in the block or entire file. Using the SED command to actually replace the strings and finally printing out the file.

User Input

Firstly, we will need the name of the file with which we are going to perform the string replacement operation. Also, we’ll need to input the actual strings to be replaced in the file. We will use the read function that prompts the user with an appropriate message and store it in the variable. 

#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the old string to be replaced : " old
read -p "Enter the new string to be replaced : " new

Replacement choice (if/else)

After the string and file input, we need to prompt the user to replace the string in the entire file or in between specific lines in the file. For that we can make use of if-else conditional statements. First, we’ll replace the string in the entire file, as a yes/no question. If it’s yes, replace the string in the entire file, else input the start and end lines of the file where the string needs to be replaced. 



#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the old word to be replaced : " old
read -p "Enter the new word to be replaced : " new

echo -e "\nFile" $file "before replacement\n\n" 
echo -e '\n... Opening' $file ' ...\n\n'
cat $file
echo -e '\n'

read -p "Do you want to replace the string in entire file ? (y/n) : " yn 
if [[ $yn == 'y' || $yn == 'Y' ]]; then
    #replace string in entire file

elif [[ $yn == 'n' || $yn == 'N' ]]; then
    read -p "Enter the line number to start replacement from : " start
    
    # replace string in between mentioned lines only
    read -p "Enter the number of lines after start to end the replacement : " end
else
    echo -e '\nInvalid Input\n'
    echo -e '\nNo changes applied\n'
fi

In the above code, we have made an if-else block that prompts a y/n question and does the replacement accordingly. The main aspect of replacing the string in the file is covered in the next section.

SED Command

The sed command stands for stream editor, and is quite a powerful tool for editing files or texts in a quick way using commands and without opening a text editor. It will be the main aspect of replacing the string operation.  We can now replace the old string with the new string using the sed command in the following format :

sed -i "s|$old|$new|g" $file

The above is a SED command that takes the three variables in bash and replaces the string in the entire file. The -i parameter makes changes directly to the original file name provided at the end. The s keyword specifies that the operation performed in the following command is substitution. The g parameter indicates applying a substitution along the entire line. We can also specify the changes to be made only to specified lines using the following format :

sed -i "4,+7 s|$old|$new|g" $file

The above command substitutes the string from the 4th till the 11th line(4+7=11th line). The sed command can be used according to the use case and as peer substitution. The above command starts with the line number and stops until the counter reaches the value minus one i.e the counter is a 0 based index. If you just want to replace a single line, you can use a line number with +0 indicating only one line and so on.

In the end, we’ll print the file with the replacement made and end the script. Also, print error if the input was not valid.

Script

#!/bin/bash
read -p "Enter the file name : " file
read -p "Enter the old word to be replaced : " old
read -p "Enter the new word to be replaced : " new

echo -e "\nFile" $file "before replacement\n\n" 
echo -e '\n... Opening' $file ' ...\n\n'
cat $file
echo -e '\n'

read -p "Do you want to replace the string in entire file ? (y/n) : " yn 
if [[ $yn == 'y' || $yn == 'Y' ]]; then
    sed -i "s|$old|$new|g" $file

elif [[ $yn == 'n' || $yn == 'N' ]]; then
    read -p "Enter the line number to start replacement from : " start
    read -p "Enter the number of lines after start to end the replacement : " end
    sed -i "$start,+$end s|$old|$new|g" $file
else
    echo -e '\nInvalid Input\n'
    echo -e '\nNo changes applied\n'
fi
echo -e '\n... Opening' $file ' ...\n\n'
cat $file
echo -e '\n'

The above script can substitute the string entirely in the file or can ask for a range of lines to replace. The sed commands are used with variables such as new, old, which are strings, and start and end, which are the number of lines used to replace the text in the file.

Script Screenshots

In the above screenshot, the “win” string is replaced with “new” in the entire file. The script prints the file before and after replacing it for the reference of the user.

In the above screenshot, the “fold” string is replaced with “gold” on only the 3 lines from 4 to 6. Hence, the replacement worked in both the entire file and between lines as well.

 So, from the above scripts, we were able to replace the strings in the file. If the input string is not found, it will not change the content of the file and return it as it is. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :