CyberKeeda In Social Media

SED: How to comment or nullify N number of starting lines of a file using SED




Lets take an example of simple nagios host config file.

Example file name : localhost.cfg
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
        contacts                nagiosadmin
        }
        
define host{
        use                     windows-server                    
        host_name               windows
        alias                   windows-srv
        address                 10.0.0.1
        contacts                nagiosadmin
        }
Here I want to comment starting 8 lines of my file to make it invalid

to nullify the string values my localhost.cfg should  look like below.
## Define a host for the local machine
#define host{
#        use                     linux-server                    
#        host_name               localhost
#        alias                   localhost
#        address                 127.0.0.1
#        contacts                nagiosadmin
#        }
        
define host{
        use                     windows-server                    
        host_name               windows
        alias                   windows-srv
        address                 10.0.0.1
        contacts                nagiosadmin
 Here we go, we will use SED to add   #  at the beginning of line for starting 8 lines

Using sed to add string on seventh line.
cybeerkeeda@Linux-Maniac:~ sed -i '1,8 s:^:#:' localhost.cfg
Change number 8 with your desired line number and # with your desired word or string


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 '1,8 s:^:#:' localhost.cfg


No comments:

Post a Comment

Designed By Kunal Saha