0

I'm trying to select an IP address from a routing table and am not having much luck crafting a sed or grep expression.

I have the below regex that is valid and selects group 1 as expected in regex testers.

.*0\.0\.0\.0\/0.*(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b).*eth0.*

I've been able to easily get the output I need via awk, however the bash variable is null when the script is executed in my environment. I've tried various expressions with sed and awk, but there seems to be more selectors required than I'm familiar with

/usr/bin/vtysh -c 'show ip route' |
sed -n 's/.*\(\b\d\{1,3\}\.\d\{1,3\}\.\d\{1,3\}\.\d{1,3}\b\).*eth0.*/\1/p'

The input is below

Codes: K - kernel route, C - connected, S - static, R - RIP,
       O - OSPF, I - IS-IS, B - BGP, E - EIGRP, N - NHRP,
       T - Table, v - VNC, V - VNC-Direct, A - Babel, D - SHARP,
       F - PBR, f - OpenFabric,
       > - selected route, * - FIB route, q - queued route, r - rejected route

S>* 0.0.0.0/0 [210/0] via 9.16.24.1, eth0, 1d06h57m
S>  0.0.0.0/0 [300/0] via 9.16.26.1, eth1, 1d06h57m
O>* 10.0.0.0/19 [110/42] via 10.255.255.21, eth1, 1d06h56m
  *                      via 10.255.255.22, eth1, 1d06h56m

expected output:

9.16.24.1
0

I think this is a job for grep (GNU) or awk, rather than sed:

grep -Po "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(?=, eth0)" file

Ouput:

9.16.24.1
  • This got me on the right track. I also found how to reset the selector when lookahead is not fixed length with \K: /usr/bin/vtysh -c 'show ip route' | grep -Po "^.*0\.0\.0\.0\/0.*via \K[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}(?=, eth0)" which filters for the specific default gateway I'm looking for. – ACiD GRiM Dec 18 '19 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.