Main menu

Linux sed command with examples

Linux sed(stream editor) is used to manipulate the content in a text file. Let’s learn sed command  with examples

Linux sed substitution

By default sed only substitute first occurrence of match,

$sed 's/windows/linux/' myfile.txt

Substitute all the occurrence of matches

 $sed 's/windows/linux/g' myfile.txt

If We want to substitute second occurrence of match

$sed 's/windows/linux/2' myfile.txt

If we want  substitute 3 match onward

$sed 's/windows/linux/3g' myfile.txt

Only print the lines which are replaced.

$sed 's/windows/linux/p' myfile.txt

Multiple sed instances

$sed -e 's/windows/linux/p' myfile.txt -e 's/microsoft/gnu/p' myfile.txt

Printing the second line

$sed '2p' myfile.txt

printing except line second

$sed '2!p' myfile.txt

Printing the second and fourth line

$sed '2,4p' myfile.txt

removing blank lines

$sed -e '/^$/d' myfile.txt

 

 

 

FacebookTwitterGoogle+RSS