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

http://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"

[email protected]:~/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

Related concept:   Difference between Python range and xrange functions?

Example

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

Output:

[email protected]:~/code/sh$ sed -i '4i This is my 4th line' ade
[email protected]:~/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:

[email protected]:~/code/sh$ sed -i '5a This is my 6th line' ade
[email protected]:~/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                 

Related concept:   PFOTD: Python cmp() builtin function examples

Keep visiting linuxnix.com for more how-tos.