- Published on
Replace Text Using the Sed Command
How to find and replace text in a file using the command line on Ubuntu/Linux.
We can use a utility called sed.
Sed itself is a stream editor that can be used to read or edit one or more files.
We can use the following command to find and replace text on Ubuntu.
In this case, we are trying to replace the word old_text with new_text in the file file.txt:
sed -i 's/old_text/new_text/g' file.txt sed is the command from the utility itself,
the -i option (which means in-place) tells sed to write changes directly to the original file.
The substitution expression (inside the quotes) has the following meaning:
- s : The beginning of the substitution expression
- old_text : Represents the word or substring to be replaced (can also be a regular expression / RegExr).
- new_text : The replacement word or substring for the old text.
- g : Represents global, which means replacing all occurrences of the matched word.
- i : Represents ignoreCase, meaning case-insensitive search and replace. The i expression is placed after the g (global) expression.
For example, suppose our current working directory is /var/www/ and we have a file named "sample.txt" in it, which only contains the text "Hello World".
Now if we want to replace every occurrence of the word "Hello" with "Hi" in the file "sample.txt", we can simply use the following sed command:
sed -i 's/Hello/Hi/gi' sample.txt Or, we can also use the absolute (full) path with the following command:
sed -i 's/Hello/Hi/gi' /var/www/sample.txt