The sed command with the s (substitue) option can be used to change text in a file or a variable. Let's say that file.txt contains the text Hello World.
The sed command with the s (substitute) flag is used to replace data. In this example, the text "Hi" will be replaced with the text "Hello". It is also important to recongize 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/' file.txt Hi World
The -i or --in-place option will actually change the content of the file.
~]# sed -i 's/Hello/Hi/' file.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
The d flag can be used to delete lines in a file.
~]# sed -i '/Hello World/d' file.txt