我正在编写一个Perl脚本,其中用户从命令行运行tracert并从cli复制该脚本,然后在perl CGI脚本中提交tracert &我的脚本将tracert保存为一个文件。
然后,我一次打开一行文件,并通过Perl Regex为ip地址打开grep。
问题是:有时用户跟踪某些跃点的结果变得太大,下面是一个示例,IP地址被分成两部分(使用CR和LF ),因此我的正则表达式匹配失败。
4 2 ms 1 ms 1 ms routers.static-ABC.XYZ.net.in [165
.112.109.61]
我正在寻找一些解决方案,或者我可以删除文件的所有空白和其他空格,或者获得一个正则表达式,通过它我可以匹配两行中间的IP地址(使用CR & LF )。
如果我能以某种方式让我的程序在文件中搜索"]“,如果我没有找到它,并且在行尾有一个空格(CR & LF),那么删除空格并加入该行。这会解决我的问题。
以下是脚本的一部分:
my @array;
open(my $fh, "<", "trace.txt")
or die "Failed to open file: $!\n";
while(<$fh>) {
&match_ip($_); ##match_ip(@array);
}
close $fh;
sub match_ip()
{
if($_ =~ m/([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/g)
{
$ip = "$1\.$2\.$3\.$4";
print "$ip\n";
}
}发布于 2014-03-15 23:00:56
逐行解决方案:
#!/usr/bin/perl
use strict;
use warnings;
while(<DATA>) {
if (/(\d+(?:\.\d+){3})]$/) {
print $1 . "\n";
} else {
my $tmp;
if (/\[([\d.]+)$/) {
$tmp = $1;
} else { next; }
while(<DATA>) {
if (/([\d.]+)]$/) {
$tmp .= $1;
print $tmp . "\n";
last;
} elsif (/([\d.]+)$/) {
$tmp .= $1;
}
}
}
}
__DATA__
1 24 ms 22 ms 22 ms 1.32.202.62.cust.bluewin.ch [62.202.32.1]
2 22 ms 24 ms 22 ms 1.32.202.62.cust.bluewin.ch [62.202.32.1]
3 24 ms 23 ms 22 ms net481.bwrt2zhb.bluewin.ch [195.186
.121.1]
4 314 ms 162 ms 22 ms net125.bwrt1inb.bluewin.ch [195.186.125.71]
5 34 ms 23 ms 24 ms if114.ip-plus.bluewin.ch [195.186.0.114]
6 27 ms 29 ms 29 ms i68geb-005-gig4-2.bb.ip-plus.net [138.1
87.1
30.158]
7 39 ms 39 ms 38 ms i00par-005-pos4-0.bb.ip-plus.net [138.187.129.34]
8 38 ms 320 ms 39 ms feth2-kara-ielo.freeix.net [213.228.3.203]
9 284 ms 39 ms 39 ms feth0-bestelle.tlcy.fr.core.ielo.net [212.85.144.6]
10 90 ms 158 ms 83 ms chloe.wikimedia.org [212.85.150.132] https://stackoverflow.com/questions/22424933
复制相似问题