Using SED to delete colon to end of line after IPv4 address match

Viewed 78

The script matches private IP in file and prints the 3rd column.

The value in the 3rd column can be either IPv4 or IPv6. The IPv4 address is trailed by a ":PORT". I can run sed 's/:.*//g' but this will also impact the IPv6 address if printed. Likewise if I use mutiple FS [,:] it will print the IPv4 but only the first octet of the IPv6 address.

My solution is to strip the ":PORT" from the end of the IPv4 address

$ cat openvpn-status.log
10.13.0.27,ijegunbead-4,74.201.72.222:49911,2022-06-26 02:55:26
10.13.0.23,biddy-h-1,2803:4600:1111:17ec:a821:1a8:53ca:760d,2022-06-26 02:55:28

I have this running in a while loop, one cycle dst will == 10.13.0.27, the next == 10.13.0.23

dst1=$(egrep -w ^$dst /etc/openvpn/openvpn-status.log | awk -F'[,:]' '{print $3}')

Result:

74.201.72.222
2803

Desired Result:

74.201.72.222
2803:4600:1111:17ec:a821:1a8:53ca:760d

I tried this but no luck

dst1=$(egrep -w ^$dst /etc/openvpn/openvpn-status.log | awk -F',' '{print $3}') | sed 's/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:*//g'
4 Answers

Would this work for you?

$ awk -F, '$3~/\./{sub(/:.*$/,"",$3)}{print $3}' openvpn-status.log
74.201.72.222
2803:4600:1111:17ec:a821:1a8:53ca:760d

Solution employing sed solution as requested in question title, let file.txt content be

10.13.0.27,ijegunbead-4,74.201.72.222:49911,2022-06-26 02:55:26
10.13.0.23,biddy-h-1,2803:4600:1111:17ec:a821:1a8:53ca:760d,2022-06-26 02:55:28

then

cut --delimiter=',' --field=3 file.txt | sed '/^[0-9]*[.]/ s/:[0-9]*$//'

gives output

74.201.72.222
2803:4600:1111:17ec:a821:1a8:53ca:760d

Explanation: use cut to get 3rd field from ,-delimited file, then for every line which starts with zero-or-more digits followed by literal dot replace : and zero-or-more digits adjacent to end of line by empty string i.e. delet it

(tested in GNU sed 4.7)

Using sed

$ sed 's/\([^,]*,\)\{2\}\([^,]*\).*/\2/;/\./s/:.*//' input_file
74.201.72.222
2803:4600:1111:17ec:a821:1a8:53ca:760d
Related