regex - Extract IPv4 and IPv6 Address Ranges in Bash? -
i'm writing bash script in need extract ipv4 , ipv6 address ranges multiple strings , format per requirements before saving file.
i've got regex working fine: http://regexr.com?38jsb (not optimized, added)
however, bash throws error if use egrep states egrep: repetition-operator operand invalid
here's bash script:
#!/bin/bash regex="(?>(?>([a-f\d]{1,4})(?>:(?1)){3}|(?!(?:.*[a-f\d](?>:|$)){})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f\d]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?4)){3}))\/\d{1,2}" echo "v=abc ip4:127.0.0.1/19 ip4:192.168.1.1/32 ip4:192.168.2.50/20 ip6:2001:4860:4000::/36 ip6:2404:6800:4000::/36 ip6:2607:f8b0:4000::/36 ip6:2800:3f0:4000::/36 ip6:2a00:1450:4000::/36 ip6:2c0f:fb50:4000::/36 ~all" | egrep -o $regex how can extract both type of ip ranges in bash? what's better solution?
note: i'm using sample data testing purpose
first, single-quote regex variable assignment (regex='...').
then, use grep -po (and double-quote $regex), @broslow suggests (note -p not available on platforms (e.g., osx)) -- -p activates support pcres (perl-compatible regular expressions), required regex.
to put together:
regex='(?>(?>([a-f\d]{1,4})(?>:(?1)){3}|(?!(?:.*[a-f\d](?>:|$)){})((?1)(?>:(?1)){0,6})?::(?2)?)|(?>(?>(?1)(?>:(?1)){5}:|(?!(?:.*[a-f\d]:){6,})(?3)?::(?>((?1)(?>:(?1)){0,4}):)?)?(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)(?>\.(?4)){3}))\/\d{1,2}' txt="v=abc ip4:127.0.0.1/19 ip4:192.168.1.1/32 ip4:192.168.2.50/20 ip6:2001:4860:4000::/36 ip6:2404:6800:4000::/36 ip6:2607:f8b0:4000::/36 ip6:2800:3f0:4000::/36 ip6:2a00:1450:4000::/36 ip6:2c0f:fb50:4000::/36 ~all" echo "$txt" | grep -po "$regex" alternative: following @l'l'l's example, here's simplified solution works sample data (again relies on -p):
echo "$txt" | grep -po '\bip[46]:\k[^ ]+' variant osx, grep doesn't support -p:
echo "$txt" | egrep -o '\<ip[46]:[^ ]+' | cut -c 5-
Comments
Post a Comment