Gentoo Archives: gentoo-user

From: Andrew Udvare <audvare@×××××.com>
To: gentoo-user@l.g.o
Subject: Re: [gentoo-user] OT scripting - strip zero if between period and digit
Date: Tue, 22 Jan 2019 01:48:10
Message-Id: af5abf7b-a2d1-cf1d-5c53-620735215d05@gmail.com
In Reply to: [gentoo-user] OT scripting - strip zero if between period and digit by Adam Carter
1 On 21/01/2019 18:50, Adam Carter wrote:
2 > I need to clean up a file which has IP addresses with leading zeros in
3 > some of the octets so I need to make, say, .09 into .9
4 >
5 > How do i do that in sed/awk/whatever?
6
7 A regex would be difficult. Parser is what you want.
8
9 You could use Python's ipaddress module (Python 3.3+). It will fix your
10 IPs (below is all one line):
11
12 python -c $'import ipaddress, sys;\nfor x in sys.argv[1:]:
13 print(ipaddress.ip_address(x))' 1.02.3.4 001.002.003.004
14
15 Output:
16 1.2.3.4
17 1.2.3.4
18
19 Fix that for stdin:
20
21 python -c $'import ipaddress, sys;\nfor x in sys.stdin.readlines():
22 print(ipaddress.ip_address(x.strip()))' <<< $'1.02.3.4\n001.002.003.004'
23
24 That way you can do:
25
26 python -c $'import ipaddress, sys;\nfor x in sys.stdin.readlines():
27 print(ipaddress.ip_address(x.strip()))' < list-of-ip-addresses
28
29 I'm sure there's a nicer way with modules installed with other languages
30 but this is built into Python as of version 3.3.
31
32 Andrew

Attachments

File name MIME type
signature.asc application/pgp-signature