Let's say that foo.txt contains a value of Hello World.
foo="Hello World"
And foo.txt is owned by john.doe.
~]$ ll foo.txt
-rw-rw-r--. 1 john.doe users 224 May 1 21:40 foo.txt
The sed command with the s (substitue) option can be used to replace a pattern in a file. When the -i or --in-place flag is NOT used, the change will not actually be made. In this way, this is a sort of test that can be used to see the change, but to not actually make the change.
sed 's|Hello|Hi|' foo.txt
When the -i or --in-place flag is used, the replacement will actually be made.
sed -i 's|Hello|Hi|' foo.txt
Be aware that sometimes this may change the owner of the file, perhaps from john.doe to nobody.
~]$ ll foo.txt
-rw-rw-r--. 1 nobody users 224 May 1 21:40 foo.txt
The -c or --copy flag can be used to perserve the owner of the file.
sed --copy -i 's|Hello|Hi|' foo.txt
This is not just limited to files. sed can also be used with strings and variables. In this example, "Hello" will be replaced with the text "Hi" in the $foo variable. Again, when the -i or --in-place flag is NOT used, the change will not actually be made.
echo $foo | sed 's|Hello|Hi|'
. . .
Hi World
With this syntax, Hello will be replaced with Hi in the foo variable.
foo=$( sed "s|Hello|Hi|" <<< "$foo" )
This does the same.
foo=$( echo "$foo" | sed "s|Hello|Hi|" )
Replace multiple instances of a string (global)
If a variable 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 foo contains the following text.
foo="
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.
~]# echo $foo | sed 's/Hello/Hi/'
Hi World
Hello World
Hello World
The g (global) flag will change every instance of Hello to Hi.
~]# echo $foo | sed 's/Hello/Hi/g'
Hi World
Hi World
Hi World
Multiple different replacements
In this example, Hello becomes Hi and World becomes Earth, in a single inline command.
echo $foo | sed 's|Hello|Hi|; s|World|Earth|'
. . .
Hi Earth
Did you find this article helpful?
If so, consider buying me a coffee over at