Search code examples
awksedtext-processing

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


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'

Solution

  • 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