Mahadev Patil Mahadev Patil - 6 months ago 6x
Bash Question

How to find & replace a pattern with string in ruby?

My file is:

[root@test etc]# cat nrpe.cfg

command[check_users]=/usr/local/nagios/libexec/check_users -w 30 -c 35
command[check_load]=/usr/local/nagios/libexec/check_load -w 15,10,5 -c 30,25,20
command[check_disk]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p /dev/sda1
command[check_hda]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p /dev/sdb
command[check_procs]=/usr/local/nagios/libexec/check_procs -w 200 -c 250

I Want to replace /dev/sdb with /dev/xvda1 in ruby


you can use gsub or sub depending on number of occurrences in a line:

line = "command[check_hda]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p /dev/sdb"
line.gsub("/dev/sdb", "/dev/xvda1")
#=> "command[check_hda]=/usr/local/nagios/libexec/check_disk -w 20% -c 10% -p /dev/xvda1"

Since its in a file, you can iterate over as:"/your/file", "r") { |file| file.each_line { |line|
puts line.gsub("/dev/sdb", "/dev/xvda1")