SED - Substitution

Ask a question

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

SED - Numbering lines
Converting DOS/UNIX and vice-versa