Shell Script to Perform String Replacement in a File
Last Updated :
09 Feb, 2022
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'
if
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.
Similar Reads
Shell Script to Perform Operations on a File
Most of the time, we use shell scripting to interact with the files. Shell scripting offers some operators as well as some commands to check and perform different properties and functionalities associated with the file. For our convenience, we create a file named 'geeks.txt' and another .sh file (or
5 min read
Shell Script to Read Data From a File
File reading is quite an important task in a Programmer's life as it makes some tasks quite comfortable and automates certain repetitive and time-consuming things. File reading is quite an interesting concept to learn as it gives insight into quite a lot of things that can be done in the Programming
3 min read
Shell Script to Join a String
There are different ways to concatenate strings in the shell. Some of them are listed below. String concatenation is used in shell scripting to make it much easier for the user to understand and use the program. Appending strings also allow the programmer to learn the working of concatenation on the
3 min read
String Manipulation in Shell Scripting
String Manipulation is defined as performing several operations on a string resulting change in its contents. In Shell Scripting, this can be done in two ways: pure bash string manipulation, and string manipulation via external commands. Basics of pure bash string manipulation: 1. Assigning content
4 min read
Shell Script to Concatenate Two Strings
String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other. The examples below show some shell scripts that can be used to concatenate strings. E
3 min read
Shell Script to Perform Database Operations
In this article, we will be creating a shell script to perform various database operations. We will be using the MySQL database management system and the MySQL command-line client for our examples. However, the concepts and techniques discussed in this article can be applied to other database manage
5 min read
How to UPDATE and REPLACE Part of a String in SQLite
In SQLite, updating and replacing parts of a string can be a common task, especially when dealing with textual data. SQLite, serverless architecture offers various methods to solve this problem. In this article, We will learn about string replace in a query with the help of various methods to know h
4 min read
Shell Script to Split a String
Shell Scripting or Shell Programming is just like any other programming language. A shell is a special program that provides an interface between the user and the operating system. In Linux/Unix the default shell used is bash and in windows, it is cmd(command prompt). We use the terminal to run a sh
3 min read
Batch Script - Replace a String
In this article, we are going to Replace a substring with any given string. Batch Script :@echo off set str=GFG is the platform for geeks. echo %str% set str=%str:the=best% echo %str% pause In the above example, we are going to replace 'the' by substring 'best' using %str:the=best% statement. Explan
2 min read
How to UPDATE and REPLACE Part of a String in SQL Server
In SQLServer, efficient manipulation of strings is crucial for managing databases effectively. Among the fundamental operations are updating and replacing parts of strings within tables. These operations are invaluable for correcting data inconsistencies, enhancing data quality, and transforming tex
4 min read