我有以下包含很多条目的文件:
[...]
edit "ip_address_1"
set uuid 8b6d9bd0-9fe7-51ee-d54d-d904bfc9a7e1
set associated-interface "interface1"
set subnet 10.0.0.1 255.255.255.255
next
edit "ip_address_2"
set uuid a3465e68-9fe7-51ee-cf95-96b35ab0532e
set associated-interface "interface1"
set subnet 10.0.0.2 255.255.255.255
next
edit "ip_address_3"
set uuid c1b62e20-9fef-51ee-5915-14502d40552e
set associated-interface "interface2"
set subnet 10.0.0.3 255.255.255.255
next
我想使用 awk 脚本删除所有不包含的块
set associated-interface "interface1"
所以最终结果应该是
edit "ip_address_1"
set uuid 8b6d9bd0-9fe7-51ee-d54d-d904bfc9a7e1
set associated-interface "interface1"
set subnet 10.0.0.1 255.255.255.255
next
edit "ip_address_2"
set uuid a3465e68-9fe7-51ee-cf95-96b35ab0532e
set associated-interface "interface1"
set subnet 10.0.0.2 255.255.255.255
next
我尝试过这样的事情
awk '/edit/, /next/ {if ($0 ~ /set associated interface1/) {print $0}}' address.fgt
但输出仅包含以下行:
set associated interface1
set associated interface1
相反,我想要全部阻止。
有什么提示吗?
gnu-awk
解决方案:
awk -v RS='\nnext\n' '{ORS = RT} /set associated-interface "interface1"/' file
edit "ip_address_1"
set uuid 8b6d9bd0-9fe7-51ee-d54d-d904bfc9a7e1
set associated-interface "interface1"
set subnet 10.0.0.1 255.255.255.255
next
edit "ip_address_2"
set uuid a3465e68-9fe7-51ee-cf95-96b35ab0532e
set associated-interface "interface1"
set subnet 10.0.0.2 255.255.255.255
next
详情:
RS='\nnext\n'
将输入记录分隔符设置为
next
两边换行
ORS = RT
:设置输出记录分隔符与输入记录分隔符相同
/set associated-interface "interface1"/
打印包含该子字符串的每条记录
第二个解决方案(适用于任何 awk 版本):
awk '/^edit / {
rec = 1
s = $0
next
}
rec {
s = s ORS $0
}
/^next/ {
if (s ~ /set associated-interface "interface1"/)
print s
rec = 0
}' file
edit "ip_address_1"
set uuid 8b6d9bd0-9fe7-51ee-d54d-d904bfc9a7e1
set associated-interface "interface1"
set subnet 10.0.0.1 255.255.255.255
next
edit "ip_address_2"
set uuid a3465e68-9fe7-51ee-cf95-96b35ab0532e
set associated-interface "interface1"
set subnet 10.0.0.2 255.255.255.255
next