regex - Perl search and replace substring -
how can search , replace substring using perl script?
for example --> txt1.txt
hi/hello #55 hi/hi #55
how can search variable1 in txt1.txt, if found replace variable2. there can number after hashtag between 0-100. search "hi/hello" first , if found, replace whole content "hi/hello #(0-100)" "hi/hello #60;
mytry.txt
my $variable1="hi/hello #(0-100)"; $variable2="hi/hello #60; print "$short\n"; system(q{perl -pe"s|($env{variable1} *)#\d+|$env{variable2}|;" txt1.p4sm > txt2.p4sm});
desiredoutput.txt
hi/hello #60 hi/hi #55
what doing doesn't make sense, if inside of perl script don't shell out perform perl one-liner, write simple loop solve problem.
the easiest way create pattern matches like, perform substitution on line-by-line basis. example below uses data
filehandle, can replaced filehandle pointing source file modify:
use strict; use warnings; $pattern = qr|(hi/hello) #\((\d{1,3})\)|; while ( $row = <data> ) { # enforce restriction 0-100 if ( $row =~ m/$pattern/ && $2 >= 0 && $2 <= 100 ) { # replace new suffix print $row =~ s/$pattern/$1 #(60)/gr; next; } print $row; } __data__ hi/hello #(1) hi/hello #(10) hi/hello #(100) hi/hello #(101)
output:
hi/hello #(60) hi/hello #(60) hi/hello #(60) hi/hello #(101) <- ignored because doesnt fall range [0, 100]
regular expression explained:
(hi/hello) #\((\d{1,3})\)
this regular expression matches , captures 2 pieces of data, prefix "hi/hello" , number inside of #(<number>)
. these stored in $1
, $2
respectively.
Comments
Post a Comment