You are currently viewing sed command in Linux

sed command in Linux

sed command in Linux 

sed command full form is Stream Editor it is one of the useful utility in Linux .It is sed for text substitution,manipulations,find and replace,inserting ,deleting or searching text.

syntax

sed option [ecript] [inputfile]

1 View partial text of a file

sed -n 2,9p file.txt

it will not display complate file as we use -n option & option p will print lines from 2 to 9.


2 display complete file with remove some line

sed 2,9d file.txt

it will remove line 2 to 9 as we used here d option


3 Deleting a line

sed Nd file.txt

N is the line number & d for deleting line number.


4 delete the last line

sed $d file.txt


5 Searching and Replacing a string

sed ‘s/unix/linux/’ file.txt

s is for searching a word unix & replace it with linux on every line for the first occurrence only.


6 Searching and Replacing a string from whole file

sed ‘s/unix/linux/g’ file.txt

here we used g option


7 Searching and Replacing the nth occurrence of string

sed ā€˜s/unix/linux/2gā€™ file.txt

it will replace 2nd occurrence of every line from complete file


8 Searching and Replacing a string for particular line

sed ‘4 s/unix/linux/’ file.txt

it will replace on 4th line


9 Adding a line

To add a new line with some content after every pattern match, use option ā€˜aā€™ , we use a option to add new line after pattern match and i to add new line before pattern match

sed ‘/linux/a “text after match”‘ file.txt

sed ‘/linux/i “text before match” ‘ file.txt


10 Changing a whole

we use c option for changing complte line after pattern match

sed ‘/linux/c “new line added” ‘ file.txt


11 Making a backup copy

we use i option for keeping backup 

sed -i.bak -e ‘s/unix/linux/g’ file.txt


12 Appending lines

this is useful for appending line

sed -e ‘s/.*/adding word &/’ file.txt

now every line start with adding word


You May Also Enjoy Reading This …

Leave a Reply