Replace String in File
To replace a string in file with new value in Bash Script, we can use sed command. sed command stands for stream editor and is used for search, find and replace, insert or delete operations.
In this tutorial, we will use sed command to replace string in a file with new value, with example bash scripts.
Syntax
The syntax to replace a string with new string value in Bash using sed command is
sed -i "s/old/new" filename
where
Command/Value | Description |
---|---|
sed | command |
-i | Option to specify that files are to be edited in place. |
s | s command stands for substitute. If found, replaces old value with new value. |
old | A string or regular expression to match old value. |
new | A replacement value for the old string. |
filename | File in which the content has to be searched for old value and replace with new value. |
If you are working on Mac to run the Bash script, then we need to specify backup extension as well, as shown in the following.
sed -i.backupext "s/old/new" filename
where backupext is the extension for back up file. Original file will be modified with the search and replacement operations. In addition to this, a backup file with the given extension to original file name will be created.
Specifying backup extension is mandator in Mac, while optional in Linux/Unix systems.
Examples
Replace All Occurrences of String in File
In this example, we have a data.txt file. We will use sed command to replace the string "hello"
with the string "apple"
in this data.txt file.
data.txt
hello world
hello user
Example.sh
old="hello"
new="apple"
filename="data.txt"
sed -i "s/$old/$new/" $filename
Execute this bash script, and the contents of the file will be modified with the old string replaced by new string.
data.txt
apple world
apple user
Are you working on Mac
If you are working on Mac with Bash shell, as already mentioned in the syntax, we need to specify backup extension.
data.txt
hello world
hello user
Example.sh
old="hello"
new="apple"
filename="data.txt"
sed -i.bak "s/$old/$new/" $filename
Execute this bash script, and the contents of the file will be modified with the old string replaced by new string.
data.txt
apple world
apple user
data.txt.bak
hello world
hello user
Conclusion
In this Bash Tutorial, we have learnt how to iterate over items of an array using While loop.