On 21/01/2019 18:50, Adam Carter wrote:
> I need to clean up a file which has IP addresses with leading zeros in
> some of the octets so I need to make, say, .09 into .9
> 
> How do i do that in sed/awk/whatever?

A regex would be difficult. Parser is what you want.

You could use Python's ipaddress module (Python 3.3+). It will fix your
IPs (below is all one line):

python -c $'import ipaddress, sys;\nfor x in sys.argv[1:]:
print(ipaddress.ip_address(x))' 1.02.3.4 001.002.003.004

Output:
1.2.3.4
1.2.3.4

Fix that for stdin:

python -c $'import ipaddress, sys;\nfor x in sys.stdin.readlines():
print(ipaddress.ip_address(x.strip()))' <<< $'1.02.3.4\n001.002.003.004'

That way you can do:

python -c $'import ipaddress, sys;\nfor x in sys.stdin.readlines():
print(ipaddress.ip_address(x.strip()))' < list-of-ip-addresses

I'm sure there's a nicer way with modules installed with other languages
but this is built into Python as of version 3.3.

Andrew

Attachment: signature.asc
Description: OpenPGP digital signature

Reply via email to