‘sed’ for Search & Replace in Single or Multiple Files


‘sed’ for Search & Replace in Single or Multiple Files

sed stream editor – A Powerful Text Stream Editor

sed ‘search-text’/replace-text’


$ sed -i ‘s/AnanovaSitegeek/g’ /home/ananova/index.php

This command would open index.php and line-by-line would replace all the occurrences of Ananova with Sitegeek.

Search & Replace in Vim

-i‘ in-pace edit, i.e., no need to redirect the output from sed to new file

g‘ global replacement to replace all occurrences once per line

Replacing nth occurrence

Use the ‘/1’, ‘/2’ instead of ‘/g’ flags to replace the first or second occurrence of the pattern in a line.

s,‘ to specify the range, when the scale is determined ‘g’ option omitted

$ sed ‘1,3 s/AnanovaSitegeek/g’ /home/ananova/index.php

The sed command replaces the lines with a range from 1 to 3.

%‘ for the entire document

‘$’ indicates last line in the file

$ sed ‘2,$ s/AnanovaSitegeek/g’ /home/ananova/index.php

The sed command replaces the text from the second line to the last line in the file.

Esc Press Shitft : and provide the following command to provide one tab before line

:s/^/\t/


Parenthesize first character of each provide provided as on output of echo command through the pipe:


echo “Web Hosting Industry Demystified” | sed ‘s/\(\b[A-Z]\)/\(\1\)/g’

(W)eb (H)osting (I)ndustry (D)emystified

To replace the string on a specific line number


$ sed ‘3 s/AnanovaSitegeek/g’ /home/ananova/index.php


The above sed command replaces the string only on the third line.

Deleting Lines from File

Delete the last line

$ sed ‘$d’ index.php

Delete a particular line say n 

$ sed ‘nd’ index.php


$ sed ‘3d’ filename.txt

Delete line from range x to y

$ sed ‘x,yd’ index.php


$ sed ‘12,15d’ index.php

Delete from nth to the last line

$ sed ‘nth,$d’ index.php


$ sed ’10,$d’ filename.txt

Delete pattern matching line

$ sed ‘/pattern/d’ index.php


$ sed ‘/flowentry/d’ index.php

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.