Description
When we are managing a Ubuntu/Linux machine, we may sometimes get into a situation where we need to find and replace a specific text in a file.
We can do that using the SED (SED stands for Stream Editor) utility using a command-line tool.
Syntax
Here is the basic syntax of the SED utility to find and replace a specific text in a file.
- The option
-i
tells the SED editor to write and changes to the original file. - The substitution expression contains the below things.
- The letter
s
represents the beginning of the substitution expression. - The word
original
represents the word or substring to replace, which can also be a regular expression. - The word
new
represents the replacement word or substring. - The letter
g
represents global, which replaces all the occurrences of the word. - The letter
i
represents ignore case, which makes the string search case-insensitive.
- The letter
> sed -i 's/original/new/gi' filename.txt'
Examples
The below command replaces all the occurrences of the word "John" with "Harry" in the "sample.txt" file in the current working directory.
sed -i 's/John/Harry/gi' sample.txt
The below command does the same but it uses an absolute path to locate the file, which starts with a forward slash /
as shown below.
sed -i 's/John/Harry/gi' /var/www/sample.txt