How can I replace all text before a match in the Perl submenu?

I read each line of the input file (IN) and print the line read into the output file (OUT) if the line starts with one of the patterns, for example "ab", "cd", "ef", "gh", "ij" and etc. The print line is in the form "pattern: 100" or form "pattern: 100: 200". I need to replace "pattern" with "myPattern", i.e. Print the current line in FILE, but replace all the text before the first appearance of ":" with "myPattern". What is the best way to do this?

I currently have:

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

I'm not sure if substr substr will help, because the "pattern" can be "ab" or "cd" or "ef" or "gh" etc.

Thank! Bi

+3
source share
6 answers
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");
}

My perl is a little rusty, so the syntax may not be accurate.

edit : Put it in a function for ya.

0
source

In general, do the following:

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}:/;
}

The sort sets the longest first, so if the data has ab :: and both ab and ab: are replaced, ab: is used instead of ab.

+3
source

Perl (a) , (b) (c) true, , false, .

:

while ( <IN> )
{ 
    if (s/<pattern1>:/<replace1>/ ||
        s/<pattern2>:/<replace2>/) {
       print FILE;
    }
}

. , - .

+1
while ( <IN> )
{ 
  s/^pattern:/myPattern:/;
  print OUT
}
0

, :

$expr = "^(ab)|(cd)|(ef)|(gh)|(ij)";
while (<IN>)
{
    if (/$expr:/)
    {
        s/$expr/$myPattern/;
        print FILE;
    }
}
0

, , , .

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

Any left side patterns will be replaced. If the left side does not match, nothing will be printed.

0
source

Source: https://habr.com/ru/post/1531269/


All Articles