A few words of thanks would be greatly appreciated.

SED - Substitution

The substitute command:[ s. ]changes all occurrences of the regular expression into a new value.

Basic Substitution


1st match (each line) encountered only

sed 's/la/LA/' file.txt


All occurrences (each line) encountered
sed 's/la/LA/g' file.txt


Only the 2nd occurrence (each line) encountered
sed 's/la/LA/2' file.txt

Conditioned Substitution


/explanation/ - Only if the line contains "explanation"
sed '/awk/ s/sed/SED/' file.txt

Number of line - Only line no "N"
sed '18 s/sed/SED/' file.txt

/Regex/ - Only if there is correspondence with the regular expression
sed '/^[ ][Ss]ed/ s/ed/ED/g' file.txt


0,/regex/ - Only the 1st case found

sed '0,/sed/ s//SED/' file.txt


/explanation1/,/explanation2/ - Only in between "explanation1 - explanation2"
sed '/start/,/End/ s/ed/ED/' file.txt # Only the 1st case found

sed '/Start/,/End/ s/ed/ED/g' file.txt # all case

8,13 - Only in between lines 8 to 13

sed '8,13 s/ed/ED/g' file.txt

We can also combined reason and line

sed '8,/End/ s/ed/ED/g' file.txt
sed '/Start/,13 s/ed/ED/g' file.txt

Or with "regex"
sed '/Start/,$ s/ed/ED/g' file.txt # to the end($)
sed '/^[ ][Ss]ed/,13 s/ed/ED/' file.txt

Advanced Use

Replace any text between 2 grounds excluding grounds
sed  '/Start/,/End/{ /Start/b;/End/b; s/.*/SED - The Stream ÉDitor/; }' file.txt

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
This document, titled « SED - Substitution », is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).

Subscribe To Our Newsletter!

The Best of CCM in Your Inbox

Subscribe To Our Newsletter!