2014-07-25 27 views
0

我需要從所有IP地址中刪除csv中的所有前導零,但不能刪除其他(如主機名)。只在IP地址中刪除前導零

我得到了下面,這並刪除所有

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

樣本CSV:

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

應該成爲

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

任何想法?

+2

一個例子會更好。 –

+0

我在CSV示例之前和之後附加了一個。 – Stef

回答

2

嘗試Regexp::CommonNet::IP,如果你不介意使用CPAN模塊。

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

這適用於您的數據。例如:

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 

打印:

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

在任何情況下,我強烈建議您使用CPAN模塊來解析CSV文件,像Text::CSV。下面

+1

好吧,明白了。但我一直在尋找更多的一般方法,不依賴IP來進入第一列。 – Stef

-1

UNIX的正則表達式可以幫助:

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

試試這個:

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