1

我最近制作了一个 shell 脚本来自动化将文件加载到 snmp 守护进程中的所有步骤。

最后我需要在服务器上编辑一个 conf 文件,我意识到我需要使用正则表达式。

我创建了一个名为zfiles.txt的文件,其中包含我需要插入到特定行范围内的所有内容。

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

我需要snmptt_conf_files = <<ENDEND.zfiles.txt

顺便说一句,如果有人可以提供一些好的资源来学习正则表达式,我将不胜感激。

提前致谢

4

2 回答 2

2

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.

于 2013-05-03T00:03:26.080 回答
1
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.

于 2013-05-03T00:03:44.087 回答