Regular expression to replace a part of a config file

I recently made a shell script to automate the process of loading a file into snmp daemon with all the steps.

In the end I need to edit a conf file on the server, and I realize I need to use regular expressions.

I have made a file named zfiles.txt where I have all the content I need to insert into a certain range of lines.

snmptt_conf_files = <<END
/etc/snmp/file-1
/etc/snmp/file-2
...
...
/etc/snmp/file-n  
END

I need to replace everithing between snmptt_conf_files = <<END and END with the content of zfiles.txt.

BTW if anyone can provide some good resources to learn regular expressions, I would really appreciate it.

Thanks in advance

Answers


sed '/snmptt_conf_files = <<END/,/END/{     # for a here-doc block:
  /^END$/b          # if at the end skip rest
  /<<END/!d         # if not first line delete and skip rest... else insert file:
  r zfiles.txt
}' input

As for the resource, Mastering Regular Expressions by Jeffrey E F Friedl is a solid book.


I came up with an awk (gnu) one-liner, hope it helps:

 awk 'NR==FNR{r=$0;next}/END$/&&!f{print;f=1;next}!f{print}/END$/&&f{print r $0;f=0}' RS="\0" zfile.txt RS="\n" file

let's test a little bit:

kent$  cat file
snmptt_conf_files = <<END
/etc/snmp/file-1
/etc/snmp/file-2
...
...
/etc/snmp/file-n  
END

keep1
keep2
keep3

snmptt_conf_files = <<END
/etc/snmp/file-1
/etc/snmp/file-2
...
...
/etc/snmp/file-n  
END

kent$  cat zfile.txt
replace1
replace2
replace3

now execute the one-liner:

kent$  awk 'NR==FNR{r=$0;next}/END$/&&!f{print;f=1;next}!f{print}/END$/&&f{print r $0;f=0}' RS="\0" zfile.txt RS="\n" file
snmptt_conf_files = <<END
replace1
replace2
replace3
END

keep1
keep2
keep3

snmptt_conf_files = <<END
replace1
replace2
replace3
END

it seems the one-liner does the job for you. regarding the regex resources, I think if you google it , you will get >10k result. take one you like and learning by doing.


Need Your Help

How to prevent an async method form being called twice?

ios objective-c asynchronous

I have an app that is keeping track of some data every .01 seconds. When the data (NSArray) count reaches 50 items I want to send this to the server asynchronously. The problem is that by the time ...

Printing an array with some MySQL records

php mysql html table duplicate-data

Not sure if the subject is suitable for the question.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.