I am trying to match a pattern in a file and insert a line. If the pattern matches then insert a line before the matching pattern line.
for example,
I have the following content in a file:
//This is my source file
//this is where i want to insert a line
Expand|Select|Wrap|Line Numbers
- class Class1
- {
- data members
- member functions
- }
- //this is where i want to insert a line
- class Class2
- {
- data members
- member functions
- }
This is what i have tried so far:
Expand|Select|Wrap|Line Numbers
- $presentFlag = 0;
- $notPresentFlag = 0;
- ##$ Open source file for reading the contents
- open(SOURCE,"<",$sourceFile) or die( "File not found...$!");
- ### open new file for inserting new line -> [TestFixture], after matching a pattern
- open(DEST,">",$destFilename) or die("File not found...$!");
- while($fileLine = <SOURCE>){
- if( $fileLine =~ m/public class/ ){ # pattern to be matched in source file
- if( $previousLine =~/[TestFixture]/ ){ # check for previous line if it already has new text
- print "\n Pattern already present in FN $destFilename...$previousLine";
- $presentFlag = 1;
- }
- else {
- print "\n Pattern NOT present in FN $destFilename...$previousLine";
- $notPresentFlag = 1;
- }
- }
- ##### If pattern already present then print the file contents as it is in dest file
- if($presentFlag){
- print DEST $fileLine;
- }
- ## Get the previous line here
- $previousLine=$fileLine;
- }# end of while
- ### If pattern matches and doesnt have the previous line as required
- if($notPresentFlag){
- ### I am stuck here....how do i move my insertion pointer to previous line in my source and dest file???
- ### do i need to have a counter or is there any other alternate way?
- }
- close(SOURCE);
- close(DEST);
Thanks in advance.
Regards
Pramod