Remove leading zeros in IP addresses only

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

I got the following which removes everything

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?

0


source to share


4 answers


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


source


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

      

Anyway, I highly recommend that you use the CPAN module to parse a CSV file like Text :: CSV .

+1


source


Try the following:

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

      

+1


source


The below UNIX expression can help:

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

      

-1


source







All Articles