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.


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>* [210/0] via, eth0, 1d06h57m
S> [300/0] via, eth1, 1d06h57m
O>* [110/42] via, eth1, 1d06h56m
  *                      via, eth1, 1d06h56m

expected output:

1 Answer 1


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

  • 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, 2019 at 0:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .