I have the following file with a lot of entries:
[…]
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
I’d like to use an awk script to delete all blocks which don’t contain
set associated-interface "interface1"
so the final result should be
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
I tried something like this
awk '/edit/, /next/ {if ($0 ~ /set associated interface1/) {print $0}}' address.fgt
but the output contains only the lines with:
set associated interface1
set associated interface1
instead I’d like to have the all block.
Any hints?
>Solution :
You may use this gnu-awk solution:
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
Details:
RS='\nnext\n'sets input record separator tonextwrapped with line break on both sidesORS = RT: Sets output record separator same as the input record separator/set associated-interface "interface1"/prints each record that contain this substring
2nd Solution (works in any awk version):
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