Sed is a powerful tool to do some text manipulations in a file. We already covered some basic SED stuff.

https://www.linuxnix.com/2012/04/sedsteam-editor-explained-detail-linuxunix.html

In this post we will see one simple use case of SED. I have a requirement where I have to insert a new line with some data at a particular line. We can achieve it with 'i' operator. I have following file and I want to insert a line at 4th line as "This is my 4th line"

surendra@sanne-taggle:~/code/sh$ cat ade 
    August 2015       
Su Mo Tu We Th Fr Sa  
                   1  
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31                 

Syntax:

sed -i '<line number to insert>i <Content to insert>' filename

Example

sed -i '4i This is my 4th line' ade

Output:

surendra@sanne-taggle:~/code/sh$ sed -i '4i This is my 4th line' ade
surendra@sanne-taggle:~/code/sh$ cat ade 
    August 2015       
Su Mo Tu We Th Fr Sa  
                   1  
This is my 4th line
 2  3  4  5  6  7  8  
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31                 

How about appending a line to a particular line using SED?

Use "a" operator as shown below.

sed -i '5a This is my sixth line' ade

Example output:

surendra@sanne-taggle:~/code/sh$ sed -i '5a This is my 6th line' ade
surendra@sanne-taggle:~/code/sh$ cat ade 
    August 2015       
Su Mo Tu We Th Fr Sa  
                   1  
This is my 4th line
 2  3  4  5  6  7  8  
This is my 6th line
 9 10 11 12 13 14 15  
16 17 18 19 20 21 22  
23 24 25 26 27 28 29  
30 31                 

Keep visiting linuxnix.com for more how-tos.

 

 

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.