Reputation: 625
I want to extract the lines in a file containing the range for particular subnet
Input:
subnet 172.16.31.0 netmask 255.255.255.0 {
# default gateway
option routers 172.16.31.10;
option subnet-mask 255.255.255.0;
option domain-name "aaaaaa";
option domain-name-servers 172.16.31.10;
#option nis-domain "domain.org";
range dynamic-bootp 172.16.31.80 172.16.31.90;
default-lease-time 21600;
max-lease-time 43200;
host test {
hardware ethernet 00:23:8b:42:3f:d1;
fixed-address 172.16.31.3;
}
}
subnet 172.16.31.1 netmask 255.255.255.0 {
# default gateway
option routers 172.16.31.11;
option subnet-mask 255.255.255.0;
option domain-name "aaaaaa";
option domain-name-servers 172.16.31.11;
#option nis-domain "domain.org";
range dynamic-bootp 172.16.31.80 172.16.31.90;
default-lease-time 21600;
max-lease-time 43200;
host test {
hardware ethernet 00:23:8b:42:3f:d8;
fixed-address 172.16.31.4;
}
}
I want to extract range dynamic-bootp for subnet 172.16.31.0.
Expected output:
range dynamic-bootp 172.16.31.80 172.16.31.90;
Is there any sed solution?
Update: Structure of the content will not be same, lines may get added / deleted based on config requirement
Tried -
sed -n '/^subnet 10.172.31.0 netmask/,/^}/{'
-n ' s/^\( *range dynamic-bootp\)./,/^}'
-n '}'
file
Upvotes: 1
Views: 104
Reputation: 88583
With GNU sed
and bash
:
n="172.16.31.0"
n="${n//./\\.}" # escape every dot
sed -n '/subnet '"$n"' /,/^}/ {/range/{s/^ *//p}}' file
Update to remove leading spaces and/or tabs:
sed -n '/subnet '"$n"' /,/^}/ {/range/{s/^[[:space:]]\+//p}}' file
Output:
range dynamic-bootp 172.16.31.80 172.16.31.90;
Upvotes: 3
Reputation: 34174
Assuming input is formatted as shown (eg, a subnet
block ends with a }
in column 1) ...
One sed
idea using a capture group (as OP appears to be attempting in the sample code):
myip='172.16.31.0'
sed -n -E "/^subnet ${myip} /,/^}/{s/.*(range dynamic-bootp[^;]*;).*/\1/p}" file
Where the capture group is defined by (range dynamic-bootp[^;]*;)
.
This generates:
range dynamic-bootp 172.16.31.80 172.16.31.90;
Upvotes: 2
Reputation: 5734
If your text has always that same exact structure, you could use:
grep -A9 172\.16\.31\.0 test.txt | tail -n1 | cut -d' ' -f6-
In case that the structure (amount of lines per block, spaces, etc) please add that info to the question.
Upvotes: 1