[英]How can I match text and replace it with a computed value based on the match in Perl?
[英]How can I replace all the text before the match in a Perl substitution?
我正在讀取輸入文件(IN)的每一行並將行讀取打印到輸出文件(OUT),如果該行以其中一種模式開頭,例如“ab”,“cd”,“ef”,“gh”打印的行是“pattern:100”形式或“pattern:100:200”形式。 我需要將“pattern”替換為“myPattern”,即將當前行打印到FILE,但在第一次出現“:”之前用“myPattern”替換所有文本。 做這個的最好方式是什么?
目前我有:
while ( <IN> )
{
print FILE if /^ab:|^bc:|^ef:|^gh:/;
}
我不確定substr替換是否有幫助,因為“pattern”可以是“ab”或“cd”或“ef”或“gh”等。
謝謝! 雙
通常,這樣做:
my %subst = ( 'ab' => 'newab', 'bc' => 'newbc', 'xy' => 'newxy' );
my $regex = join( '|', map quotemeta, sort { length($b) <=> length($a) } keys %subst );
$regex = qr/^($regex):/;
while ( <IN> ) {
print FILE if s/$regex/$subst{$1}:/;
}
排序首先放置最長的,因此如果數據具有ab ::並且ab和ab都被替換,則使用ab:而不是ab。
默認情況下Perl的替換運算符(a)使用第一個匹配,(b)僅替換一個匹配,(c)如果替換則返回true,否則返回false。
所以:
while ( <IN> )
{
if (s/<pattern1>:/<replace1>/ ||
s/<pattern2>:/<replace2>/) {
print FILE;
}
}
應該適合你。 請注意,由於短路,只會進行一次替換。
while ( <IN> )
{
s/^pattern:/myPattern:/;
print OUT
}
這可能是你想要的:
$expr = "^(ab)|(cd)|(ef)|(gh)|(ij)";
while (<IN>)
{
if (/$expr:/)
{
s/$expr/$myPattern/;
print FILE;
}
}
sub replacer {
$line = shift;
$find = shift;
$replace = shift;
$line =~ /([^:]+):/
if ($1 =~ /$find/) {
$line =~ s/([^:]+):/$replace/ ;
return $line;
}
return ;
}
while (<IN>)
{
print OUT replacer ($_,"mean","variance");
print OUT replacer ($_,"pattern","newPattern");
}
我的perl有點生疏,所以語法可能不准確。
編輯 :把它放在ya的函數中。
執行上述要求的最短路徑是重用代碼,但包含替換。
while ( <IN> )
{
print FILE if s/^(ab|bc|ef|gh):/MyPattern:/;
}
任何左側圖案都將被替換。 如果左側不匹配,則不會打印任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.