我在使用perl来动态替换时间戳时遇到问题。在config.pm中,我有一个时间戳的占位符:
our $PrintableTimeStamp = "20130101_010101";
我想用动态生成的当前时间戳替换数字,即
$current = $year.$mon.$mday."_".hour.$min.$sec; # (e.g., 20131230_153001)
我使用以下命令工作,
perl -p -i.bak -e s/20130101_010101/$current/g config.pm
但下面没有这个,我希望可以更通用和灵活
perl -p -i.bak -e s/\d{8}_\d{6}/$current/g config.pm
任何原因?
答案 0 :(得分:1)
您应该考虑绑定=~
,并且您可能需要在正则表达式模式中将()
预期的数字字符串分组。这是我在数据库查询中使用它之前用来验证MAC地址的正确长度的例程示例:
sub verify { #{{{ pull out the colons, verify char = 12, replace colons
my @newmac;
foreach my $hostmac (@_) {
chomp($hostmac);
if ($hostmac =~ /(?:[A-F0-9]{2}:){5}[A-F0-9]{2}/) {
push (@newmac,$hostmac);
} else {
my $count;
$hostmac =~ s/\://g; # take out the colons
if ($hostmac =~ /^.{12}$/ ) { # make sure we have a 12 character string
$hostmac = sprintf "%s:%s:%s:%s:%s:%s", unpack("(A2)6","\U$hostmac\E");
push (@newmac, $hostmac);
} else {
print "$hostmac\n";
print colored ("$hostmac should be 12 characters long\n", 'red'); die; # You FAIL!!
}
}
}
return $newmac[0] if $#newmac == 1;
return @newmac;
}