CyberKeeda In Social Media

SED : How to add specific string after N number of line in a file.




Lets take an example of simple nagios host config file.

Example file name : localhost.cfg
# Define a host for the local machine
define host{
        use                     linux-server                    
        host_name               localhost
        alias                   localhost
        address                 127.0.0.1
        }
 Here I want to add a line as  "  contacts                nagiosadmin " after address
contacts                nagiosadmin
to completely look like as
# Define a host for the local machine
define host{
        use                     linux-server                    
        host_name               localhost
        alias                   localhost
        address                 127.0.0.1
        contacts                nagiosadmin
        }
 Hence I have to add contact string at seventh ( 7 )line for the same file localhost.cfg

Using sed to add string on seventh line.


cybeerkeeda@Linux-Maniac:~ sed -i '7i\ contacts   nagiosadmin' localhost.cfg
Change number 7 with your desired line number


Note :

sed  -i  : Here -i    parameter will directly write the changes into the file.

I suggest to take a automatically take up backup during this comand.
cybeerkeeda@Linux-Maniac:~ sed -i.bak '7i\ contacts   nagiosadmin' localhost.cfg
White spaces after \ are intentional , you can remove it as per your requirement.

Without white space it would look like this.
cybeerkeeda@Linux-Maniac:~ sed -i.bak '7i\contacts nagiosadmin' localhost.cfg

 Search more SED tutorials on the go here.



No comments:

Post a Comment

Designed By Jackuna