Reputation: 158
How can I use regex to return just the first dst IP from this data?
ipv4 2 udp 17 34 src=192.168.1.76 dst=192.168.1.254 sport=198 dport=53 packets=1 bytes=65 src=192.168.1.254 dst=192.168.1.76 sport=53 dport=198 packets=1 bytes=105 mark=0 use=2
Wanted result: 192.168.1.254
What I have tried:
dst=([0-9]{1,3}\.){3}[0-9]{1,3}
This returns both the 1st and 2nd dst IPs.
Demo: https://regex101.com/r/anONgm/2
Upvotes: 0
Views: 389
Reputation: 203635
If this question was worded as just "How can I return just the first dst IP from this data?", then the answer would simply be this with GNU awk:
$ awk 'match($0,/dst=([^ ]+)/,a){print a[1]}' file
192.168.1.254
or with any awk:
$ awk 'match($0,/dst=[^ ]+/){print substr($0,RSTART+4,RLENGTH-4)}' file
192.168.1.254
That will work with any sed in any shell on any UNIX box.
btw verifying a regexp using some online tool just proves you have a regexp that works in that online tool. It's generally not useful for creating regexps to run in some other tool as they all use different regexp flavors (e.g. BRE vs ERE vs PCRE) with their own restrictions and/or extensions.
Upvotes: 2
Reputation: 866
You can try taking all characters until a whitespace. Check this;
dst=([\S]+)
Upvotes: 1