How to Use sed to Find and Replace in Bash
Aashish Sunuwar
Feb 02, 2024
-
Use
sed
Command to Find and Replace Texts in a File in Bash -
Use
sed
Command to Find and Replace Texts on All Files in Bash
Let’s look at the sed
command for finding and replacing texts in a file in Bash.
Use sed
Command to Find and Replace Texts in a File in Bash
The sed
command is a convenient stream editor tool for directly editing a file’s contents. Below is an example of finding any text and replacing it with a different word.
Example: test.txt
Life goes on and on and on.
Script:
sed -i 's/on/ON/' test.txt
Output:
Life goes ON and on and on.
The -i
option is used to edit in place on the file. The s
on the expression stands for a substitute for the given words.
However, this will substitute only the first occurrence of the word on
in the line. To replace the word in each occurrence on the line, we use global g
.
Script:
sed -i 's/on/ON/g' test.txt
Output:
Life goes ON and ON and ON.
Use sed
Command to Find and Replace Texts on All Files in Bash
The following command will find and replace text on all the .txt
files available in the same directory.
sed -i -e 's/on/ON/g' *.txt
A sed
command is a potent tool. You can learn more about it here.