如何在匹配模式后更新或插入行

时间:2018-01-03 14:26:04

标签: awk sed

我基本上需要一个awksed一个班轮来为特定的IF设备插入或编辑/替换gateway x.x.x.x/etc/network/interfaces文件(它可以是em1或p2p1或p3p1)。我正在使用ubuntu linux。

最好不要使用基于常数行号的正则表达式代码,例如在auto em1之后替换/插入第3行。

请注意,参数可能会更改为auto p2p1auto p3p1

场景1:em1不存在网关,插入新网站

auto lo
iface lo inet loopback
auto em1
iface em1 inet static
address 192.168.2.98
netmask 255.255.255.0
something random       <-- gateway x.x.x.x should be inserted before or after this for em1
auto p2p1
iface p2p1 inet static
address 192.168.2.121
netmask 255.255.255.0
gateway 192.168.2.1
auto p3p1
iface p3p1 inet static
address 192.168.2.121
netmask 255.255.255.0
gateway 192.168.2.1

场景2:编辑/替换

auto lo
iface lo inet loopback
auto em1
iface em1 inet static
address 192.168.2.98
netmask 255.255.255.0
gateway x.x.x.x       <-- should only edit or replace this one (when em1 requested)
auto p2p1
iface p2p1 inet static
address 192.168.2.121
netmask 255.255.255.0
gateway 192.168.2.1   <-- not this one (when em1 requested)
auto p3p1
iface p3p1 inet static
address 192.168.2.121
netmask 255.255.255.0
gateway 192.168.2.1   <-- or this one (when em1 requested)

感谢。

1 个答案:

答案 0 :(得分:1)

使用awk,您应该有一个明确定义的模式来分隔接口。在您的情况下,我假设它们都以“auto”开头,因此该字符串将是要使用的模式。如果您需要另一个,根据您的数据,下面的逻辑保持不变。

awk -v i="em1" -v g="192.168.1.42" '
    f && /^auto/    {print "gateway "g; f=0}
    f && /^gateway/ {print "gateway "g; f=0; next}
    $0 ~ "auto "i   {f=1}
                    {print}
    END             {if (f) print "gateway "g}
' file

您看到的区别在于next。更新时,我们致电next,但未达到此行(旧网关)的最后print次操作 插入时,我们不调用它,所以我们打印行(这是新接口的开始)

添加了最终END {}语句,以便在达到EOF且仍然f=1时打印网关行。这是为了修复我们编辑最后一个界面并且没有网关存在的情况。

相关问题