Seach a string and replace consequent lines in perl

Tuesday, March 07, 2017 0 Comments

Lets say I have C/C++  file which has some pattern in the line at the start. I also know that there will be 2 lines following the line that will match my pattern. I want to remove these three lines and add a new line which has a different string which is nothing but I want to replace a all those 3 three lines with a different line.

MTTRACE("ARG1",
      "ARG2",
     "ARG3");

//some code follows
MTTRACE("ARG1",
      "ARG2",
     "ARG3");
New fIle should look  as below:

MYTRACE(ARG);
//some code follows
MYTRACE(ARG);
Solution:

perl -pe '$x=3  if /^\s*MTTRACE.*/;
if($x>0){$x-- and undef $_;$_="MYTRACE(ARG);\n" if $x==0}' myfile.cc

0 comments: