Skip to content

sed - stream editor

The stream editor is used to parse and transform text using a simple definition. It can work on a given file or the input stream.

At first it can be used for search and replace with regular expressions:

Description Pattern Example Result
replace all sed 's/unix/linux/g' The unix system The linux system
replace from nth occurrence sed 's/a/b/3g' an altern==a==te ==a==ddress an altern==b==te ==b==ddress
use parenthes sed 's/\(\b[A-Z]\)/_\1_/g' `The Big Bang" ==T==he ==B==ig ==B==ang

Replace specific lines

Description Pattern
replace only in third line sed '3 s/unix/linux/'
replacing string on a range of lines sed '1,3 s/unix/linux/'
replace string from line to end sed '2,$ s/unix/linux/'

Delete lines

Description Pattern
delete a particular line sed '5d'
delete the last line sed '$d'
delete a range of lines sed '3,6d'
delete from line to end sed '12,$d'
delete line matching pattern sed '/abc/d'
delete line matching and next two sed '/easy/,+2d'
delete blank lines sed '/^$/d'

Show specific lines

Description Pattern
show a file by range sed -n '2,5p'
show specific line sed -n '4'p
show only the last line sed -n ‘$’p
show only the replaced lines sed -n 's/unix/linux/p'

Specialties

Description Pattern
replace newline sed ':a;N;$!ba;s/\n/,/g'
delete duplicate lines sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'

Last update: November 24, 2021