SED Tutorial with examples

SED: SED is a powerful stream editor.

SED Options :

-i : does in-place replacement
-n : no printing
-f : scriptname ( when there are large number of sed commands)

Syntax: sed command filename

SED Examples

Remove n lines from the top of a file :

sed -i nd filename

where n is the number of lines to be removed.

Search and replace all files in a directory :

for i in *; do sed -i 's/searchstring/replacestring/g' ${i};done

Search and replace all files with a find and sed command

grep -rl "searchstr" . | xargs sed -i 's/searchstr/replacestr/g'

**Replace Pattern1 with Pattern2 (First Occurrence ):

**

sed 's/pattern1/pattern2/' filename

Replace Pattern1 with Pattern2 (Whole File):

sed 's/pattern1/pattern2/g' filename

Delete All Characters From the first blank space through the end of the file:

sed 's/ .*$//' filename

eg. who | sed 's/ .*$//'

Print First 2 Lines Only:

sed -n '1,2p' filename

Print lines containing pattern only:

sed -n '/pattern/p' filename

Delete Lines 1 and 2 :

sed '1,2d' filename

Delete All Lines Containing the pattern :

sed '/pattern/d' filename

Delete 5 Lines:

sed '5d' filename

Delete Lines Containing Test or test:

sed '/[Tt]est/d'

Print Lines 20 through 25:

sed -n '20,25p' filename

Replace pattern1 with pattern2 in first 10 Lines :

sed '1,10s/pattern1/pattern2/g' filename

** Change First -1 to -5 on all lines containing pattern:**

sed '/pattern/s/-1/-5/' filename

Delete First three characters from each line of file:

sed 's/...//' filename

Delete last 3 characters from each line of file:

sed 's/...$//' filename

Print all lines from file showing non printing characters like tab:

sed -n 'l' filename

Find and Display a line with a value (eg. ;value)

sed -n '/startpattern/,/endpattern/{s/;value//p}' Filepath

Print Value Between Two patterns Exclusive:

sed 's/.pattern1(.)pattern2.*/\1/'

eg.Following code displays value between < and >

sed 's/../\1/'

Search & Replace between two tags Exclusive

sed -i "/startPattern/,/endPattern/{ /startPattern/b /endPattern/b s/searchPattern/replacePattern/g }" fileName

For Single Line :

sed -i "/startPattern/,/endPattern/{/startPattern/b;/endPattern/b; s/SearchPattern/ReplacePattern/g}" filename.txt

Eg. To Comment lines between two tags start and end :

sed -i "/start/,/end/{/start/b;/end/b;s/^/#/g}" filename.txt

Eg. To Uncomment lines between two tags start and end:

sed -i "/start/,/end/{/start/b;/end/b;s/^#//g}" filename.txt

Change SSH Port Using sed

sed -ie 's/#Port.*[0-9]$/Port 'newport number'/gI' /etc/ssh/sshd_config

or

sed -ie 's/Port.*[0-9]$/Port 'new port number'/gI' /etc/ssh/sshd_config

Get Value between parentheses :

sed -n -e '/[1](([^)])).*/s//\1/p'

Sed Delete First and Last Character:

sed 's/^.//;s/.$//'


  1. ^( ↩︎