[英]Replace multiple lines from a file with mutiple lines from another
Can I, in few commands, search and replace multiple lines in a file? 我可以用几个命令搜索并替换文件中的多行吗?
I'm trying to replace the 3 failover blocks from dhcp_primary
by the unique failover block from dhcp_secondary
, within dhcp_primary
. 我想,以取代从3块故障
dhcp_primary
以独特的故障转移块从dhcp_secondary
,内dhcp_primary
。
My goal is to copy the dhcpd.conf from a primary dhcp to the secondary (more information here: http://www.madboa.com/geek/dhcp-failover/ ). 我的目标是将dhcpd.conf从主dhcp复制到辅助dhcp(此处提供更多信息: http : //www.madboa.com/geek/dhcp-failover/ )。 The failover work only if the configuration are identical, except the failover block of course;
只有在配置相同的情况下,故障转移才能工作,当然,除了故障转移模块外,其他操作都不能进行。 as you can see is the website's example.
如您所见,是该网站的示例。 So I want to copy this file, but keep the failover information from the secondary.
因此,我想复制此文件,但保留次要服务器的故障转移信息。
Example dhcp_primary
: 示例
dhcp_primary
:
// some lines above
failover peer "A" {
...
}
failover peer "B" {
...
}
failover peer "C" {
...
}
// some lines below
Example dhcp_secondary
: 示例
dhcp_secondary
:
// some different lines above
failover peer "D" {
...
}
// some different lines below
The expected output have to be: 预期的输出必须是:
// some lines above
failover peer "D" {
...
}
// some lines below
I already can extract the failover blocks : 我已经可以提取故障转移块:
awk '/^failover/,/^}$/' dhcp_a
awk '/^failover/,/^}$/' dhcp_b
But I don't know how to continue. 但是我不知道如何继续。
Thanks in advance. 提前致谢。
Edit: more details for my goal. 编辑:我的目标的更多详细信息。
You can try: 你可以试试:
awk -f a.awk dhcp_b dhcp_a
where a.awk
is: a.awk
在哪里:
/^failover/,/^}$/{
if (NR==FNR) {
blk=blk $0 RS
next
}
if (++i==1) {
printf "%s",blk
}
next
}
NR!=FNR{ print }
This might work for you (GNU sed): 这可能对您有用(GNU sed):
sed -n '/^failover peer/,/^}/p' dhcp_b |
sed -e '/^failover peer/,/^}/!b;r /dev/stdin' -e 'd' dhcp_a
if the files are only of this structure and kind of content 如果文件只是这种结构和内容类型
NewFile=./FileName
head -1 dhcp_a > ${NewFile}
sed -n '1!{$!p;};}' dhcp_b >> ${NewFile}
tail -1 dhcp_a >> ${NewFile}
just take header and trailer of dhcp_a and block content of dhcp_b 只需获取dhcp_a的标题和尾部,并阻止dhcp_b的内容
if file is bigger (content around) use something like /failover/,/}/ as block delimiter in sed but it depend of the real content 如果文件更大(周围的内容),则使用/ failover /,/} /之类的内容作为sed中的块定界符,但这取决于实际内容
$ cat tst.awk
/^failover/ { inRec = 1 }
{
if (NR == FNR) {
if (inRec) {
rec = rec $0 ORS
}
}
else {
if (inRec) {
printf "%s", rec
rec = ""
}
else {
print
}
}
}
/^}/ { inRec = 0 }
$ awk -f tst.awk secondary primary
// some lines above
failover peer "D" {
...
}
// some lines below
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.