Remove leading zeros only in IP addresses

2019-09-07 03:36发布

问题:

I need to remoe all leading zeros in a csv from all IP addresses, but not others (like hostnames).

I got the following, which does remove all

s/(?<!\d)0+(?=\d)//g

sample CSV:

192.168.001.000,any comment,host0003.zone.com
010.001.100.000,any long 000 string,host004.zone.com

should become

192.168.1.0,any comment,host0003.zone.com
10.1.100.0,any long 000 string,host004.zone.com

Any ideas?

回答1:

Try Regexp::Common and Net::IP if you don't mind using CPAN modules.

$ <sample.csv perl -MRegexp::Common -MNet::IP -ple 's/($RE{net}{IPv4})/Net::IP->new($1)->ip/ge'


回答2:

Try this:

use strict;
use warnings;
use Data::Dumper;

for (<DATA>) {
   print join(",",map{ if($_=~/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/s){$_=~s/^0*(\d+)/$1/sg;$_=~s/^0*?\./0/sg;$_=~s/\.0+(\d+)/\.$1/sg;$_;}else{$_} } split /,/is,$_);
}

__DATA__
192.168.001.000,any comment,host0003.zone.com
010.001.100.000,any long 000 string,host004.zone.com


回答3:

This works for your example data:

use strict;
use warnings;

while(my $line = <DATA>) {
    $line =~ s/(?:^|\.)0+(?=\d)//g;
    print $line;
}


__DATA__
192.168.001.000,any comment,host0003.zone.com
010.001.100.000,any long 000 string,host004.zone.com

prints:

192.168.1.0,any comment,host0003.zone.com
10.1.100.0,any long 000 string,host004.zone.com

In any case, I strongly recommend that you use a CPAN module to parse the CSV file, like Text::CSV.



回答4:

The unix regex below may help:

',\{0,2\}\([0][0-9]\{2\}\.\)\([0-9]\{3\}\.\)\{2\}'.


标签: regex perl ip