How to use sed to append, delete and insert lines in file

In this post i am going to show you the basic usage of sed command while inserting, deleting and appending lines to file.

I have created one basic file name as data1. Below is the content of that. I am going to do operations on this file. One thing to remember here is that changes made by sed are not in place means they will not reflect in file. We have to use -i option to reflect them in file. Here -i means in place.

[root@node1 network]# cat data1
vikrant 8800
danish 10000
venky 12000

Case 1 : If we want to insert adding heading to file. Compare the output with previous one. Here heading is added before it start reading the file.

[root@node1 network]# sed ‘1i Employee Salary’ data1
Employee Salary
vikrant 8800
danish 10000
venky 12000

Case 2 : Above change will not be in file If we want to reflect that in file then use -i option.

[root@node1 network]# sed -i ‘1i Employee Salary’ data1
[root@node1 network]# cat data1
Employee Salary
vikrant 8800
danish 10000
venky 12000

Case 3 : How to add line after the first line. 

[root@node1 network]# sed -i ‘1a ————–‘ data1
[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
venky 12000

Case 4 : How to append the line at end of file. It will read the whole file at end of last line It will add the mentioned line.

[root@node1 network]# sed -i ‘$a ————–‘ data1
[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
venky 12000
————–

Case 5 : How to insert line before any specific line.  Here I am adding new line before line starting with venky.

[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
venky 12000
————–
[root@node1 network]# sed -i ‘/venky/i madhu 6000’ data1
[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
madhu 6000
venky 12000

Case 6 : Deleting the newly added line.

[root@node1 network]# sed -i ‘/madhu/d’ data1
[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
venky 12000
————–

Case 7 : Using the same scenario of 5. Adding the line after specified line.

[root@node1 network]# sed -i ‘/venky/a madhu 6000’ data1
[root@node1 network]# cat data1
Employee Salary
————–
vikrant 8800
danish 10000
venky 12000
madhu 6000
————–

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s