Guides‎ > ‎Tricks‎ > ‎

Find And Replace Text In Files

Find A String And Replace The Whole Line - Anywhere In The Line

This will find the line that contains the string:
debug_level=
and REPLACE it with:
debug_level=-1
in the file /usr/local/nagios/etc/nagios.cfg.

sed -i 's/.*debug_level=.*/debug_level=-1/g' /usr/local/nagios/etc/nagios.cfg

This is handy because someone may have commented out that line so it is ignored. It might have been #debug_level=-1 so replacing the whole line means the option is not commented out.

Find A String And Replace The Whole Line - Only If The Line Starts With

This will find the line that STARTS with the string
#host_perfdata_file_processing_interval=.*
and REPLACE it with:
host_perfdata_file_processing_interval=15
in the file /usr/local/nagios/etc/nagios.cfg.

sed -i 's/^#host_perfdata_file_processing_interval=.*/host_perfdata_file_processing_interval=15/g' /usr/local/nagios/etc/nagios.cfg

This is handy when you only want to change the line if it was commented out.

Find A String And Delete The Whole Line - Anywhere In The Line

This will find the line that contains the strings
INITIAL HOST STATE
INITIAL SERVICE STATE
and DELETE the line.

In ALL files in /usr/local/nagios/var/archvies/.

sed -i '/INITIAL.*.STATE/d' /usr/local/nagios/var/archives/*.log

The command is finding anything between the INITIAL and STATE words by using:
.*.
It's just that my file only contains lines that have HOST or SERVICE.

Find A String And Remove It

This will find the string (including the single quotes):
'perl(Test::Simple)'
and REMOVE it

In the file /tmp/nagiosxi/upgrade

sed -i 's/'\''perl(Test::Simple)'\''//g' /tmp/nagiosxi/upgrade

Find A String And Append To The End Of The Line

This will find the line that contains the strings
only_from
and APPEND the following to the end of the line:
10.25.0.0/16
To the file /etc/xinet.d/nrpe

sed -i '/only_from/s/$/ 10.25.0.0\/16/' /etc/xinetd.d/nrpe