Thursday, 15 March 2012

modify lines between two tags in perl -



modify lines between two tags in perl -

i need help replaceing lines between 2 tages in perl. have file in want modify lines between 2 tags:

some lines lines tag1 abc somelines nop nop abc somelines nop nop abc somelines tag2

as can see, have 2 tags, tag1 , tag2 , basically, want replace instances of abc nop between tag1 , tag2. here relevant portion of code doesn't replace. can please help..?

$fh; $cur_file = "file_name"; @lines = (); open($fh, '<', "$cur_file") or die "can't open file reading $!"; print "before while\n"; while(<$fh>) { print "inside while\n"; $line = $_; if($line =~ /^tag1/) { print "inside range check\n"; $line = s/abc/nop/; push(@lines, $line); } else { push(@lines, $line); } } close($fh); open ($fh, '>', "$cur_file") or die "can't open file wrinting\n"; print $fh @lines; close($fh);

consider one-liner using flip-flop operator.

perl -i -pe 's/abc/nop/ if /^tag1/ .. /^tag2/' file

perl

No comments:

Post a Comment