如何在 Perl 替换中替换匹配之前的所有文本? [英] How can I replace all the text before the match in a Perl substitution?

查看:32
本文介绍了如何在 Perl 替换中替换匹配之前的所有文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取输入文件 (IN) 的每一行并将读取的行打印到输出文件 (OUT),如果该行以其中一种模式开头,例如ab"、cd"、ef",gh"、ij"等.打印的行格式为pattern: 100"或pattern: 100:200".我需要用myPattern"替换pattern",即将当前行打印到FILE,但用myPattern"替换:"第一次出现之前的所有文本.做这个的最好方式是什么?

I am reading each line of an input file (IN) and printing the line read to an output file (OUT) if the line begins with one of the patterns, say "ab", "cd","ef","gh","ij" etc. The line printed is of form "pattern: 100" or form "pattern: 100:200". I need to replace "pattern" with "myPattern", i.e. print the current line to FILE but replace all the text before the first occurence of ":" with "myPattern". What is the best way to do this?

目前我有:

while ( <IN> )
{ 
    print FILE if /^ab:|^bc:|^ef:|^gh:/;
}

我不确定替换 substr 是否有帮助,因为模式"可以是ab"或cd"或ef"或gh"等.

I am not sure if substr replacement would help as "pattern" can be either "ab" or"cd" or "ef" or "gh" etc.

谢谢!毕

推荐答案

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 有点生疏,所以语法可能不准确.

My perl is a little rusty, so syntax might not be exact.

编辑:把它放在一个函数中.

edit: Put it in a function for ya.

这篇关于如何在 Perl 替换中替换匹配之前的所有文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆