
Let's say foo.txt contains Hello World.
Hello World
The sed command with the s (substitue) option can be used to replace data in a file or a variable. In this example, the text "Hello" will be replaced with the text "Hi". It is also important to recognize that when no options are used, the text in the file will not be changed. Instead, the result will simply be displayed in the terminal.
sed 's/Hello/Hi/' foo.txt
The -i or --in-place option will actually change the content of the file.
sed -i 's/Hello/Hi/' foo.txt
Replace multiple instances of a string (global)
If a file contains more than one occurence of a string, the g (global) option will need to be used to change every instance of the string. For example, let's say a file contains the following text.
Hello World
Hello World
Hello World
If the g (global) flag is not used, only the first instance of the word Hello will be changed.
~]# sed 's/Hello/Hi/' file.txt
Hi World
Hello World
Hello World
The g (global) flag will change every instance of Hello to Hi.
~]# sed 's/Hello/Hi/g' file.txt
Hi World
Hi World
Hi World
Delete
The d flag can be used to delete lines in a file.
~]# sed -i '/Hello World/d' file.txt
Did you find this article helpful?
If so, consider buying me a coffee over at