472,982 Members | 2,606 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,982 software developers and data experts.

Pattern matching and inserting a line in a file

Hi All

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
  1. class Class1
  2. {
  3.     data members
  4.     member functions
  5. }
  6.  
  7. //this is where i want to insert a line
  8. class Class2
  9. {
  10.     data members
  11.     member functions
  12. }
  13.  
I have to match for a pattern "Class" and insert a line before that pattern match.

This is what i have tried so far:

Expand|Select|Wrap|Line Numbers
  1. $presentFlag = 0;
  2. $notPresentFlag = 0;
  3.  
  4. ##$ Open source file for reading the contents
  5. open(SOURCE,"<",$sourceFile) or die( "File not found...$!");
  6. ### open new file for inserting new line ->  [TestFixture], after matching a pattern
  7. open(DEST,">",$destFilename) or die("File not found...$!");
  8.  
  9. while($fileLine = <SOURCE>){    
  10.     if( $fileLine =~ m/public class/ ){ # pattern to be matched in source file
  11.         if( $previousLine =~/[TestFixture]/ ){ # check for previous line if it already has new text
  12.             print "\n Pattern already present in FN $destFilename...$previousLine";
  13.             $presentFlag = 1;
  14.         }
  15.         else {
  16.             print "\n Pattern NOT present in FN $destFilename...$previousLine";
  17.             $notPresentFlag = 1;
  18.         }
  19.     }
  20.     ##### If pattern already present then print the file contents as it is in dest file    
  21.     if($presentFlag){
  22.  
  23.         print DEST $fileLine;
  24.     }
  25.     ## Get the previous line here
  26.     $previousLine=$fileLine;
  27. }# end of while
  28.  
  29. ### If pattern matches and doesnt have the previous line as required        
  30. if($notPresentFlag){
  31.     ### I am stuck here....how do i move my insertion pointer to previous line in my source and dest file???
  32.     ### do i need to have a counter or is there any other alternate way?
  33. }
  34. close(SOURCE);
  35. close(DEST);

Thanks in advance.

Regards
Pramod
Feb 19 '08 #1
5 4972
nithinpes
410 Expert 256MB
From your description, I feel this is what you need:
Expand|Select|Wrap|Line Numbers
  1.  
  2. $i=0;
  3. $test_fixture="xxxxxxxxxxxxx"; ###put your [Test Fixture]
  4. open(SOURCE,"<",$sourceFile) or die( "File not found...$!");
  5. open(DEST,">",$destFilename) or die("File not found...$!");
  6. @source=<SOURCE>;
  7. while(@source)
  8. {
  9.    if( /public class/ ) {  ##search for the pattern in each line
  10.       ### insert test fixture if previous line doesn't have it already
  11.       print DEST "$test_fixture\n" unless($source[$i-1]=~/$test_fixture/);
  12.       print DEST $_;
  13.   }
  14.   else {
  15.     print DEST $_;
  16.  }
  17.  $i++;
  18. }
  19.  
  20. close(SOURCE);
  21. close(DEST);
  22.  
  23.  
Feb 19 '08 #2
Hi

read the file contents into an array like this
Expand|Select|Wrap|Line Numbers
  1. @array = <SOURCE>;
once the file is in the array you can loop through the array and take two lines [none od them should ne null - betwwn two lines there might be blank lines, they have to be supressed]
then
Expand|Select|Wrap|Line Numbers
  1. if( $arr[i]=~ m/public class/ ) and $arr[i-1] !~ $lineToBeInserted
  2. #tthen 
  3. print DEST $arr[i-1]
  4. print DEST $lineToBeInserted
try this in this manner
Feb 19 '08 #3
KevinADC
4,059 Expert 2GB
It would help greatly if you showed the real text file you are trying to insert a line into. This part of your code makes little sense out of context and looks like it will just be wrong since you are using square brackets improperly /[TestFixture]/:

Expand|Select|Wrap|Line Numbers
  1.    if( $fileLine =~ m/public class/ ){ # pattern to be matched in source file
  2.        if( $previousLine =~/[TestFixture]/ ){ # check for previous line if it already has new text
Inserting lines into files is easily done using perls inplace editor once you learn how to get it running, which is extremely simple but few perl books or tutorials cover the use of the inplace editor. It is also extrememly fast so editing even big files should be quick.
Feb 19 '08 #4
Thanks a lot Nithin. and thanks Npidaparthy for optimized code.
I am able to achieve to some extent of what was required.
But the complexity is incresing now. I will get back in case i need any further help on this.
Kevin, please send me more information on PERL inplace editor for Windows platform. i have seen that some of the statements work only in Unix( for ex: perl -p -i.bak -e.....). Thanks in advance.

Thanks everyone.

Regards
Pramod
Feb 20 '08 #5
KevinADC
4,059 Expert 2GB
the inplace editor for Windows works the same as Unix. The only differences I am aware of is you have to define a backup extension with Windows (-i.bak) and you use double-quotes instead of single-quotes around the code part:

-e "some code here"
Feb 20 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Dariusz | last post by:
Despite looking at a number of tutorials in books and online examples on pattern matching - I can't quite get my head around it to work... so need some help. What I have now is a variable that...
176
by: Thomas Reichelt | last post by:
Moin, short question: is there any language combining the syntax, flexibility and great programming experience of Python with static typing? Is there a project to add static typing to Python? ...
3
by: Greg Lindstrom | last post by:
Hello- I'm running Python 2.2.3 on Windows XP "Professional" and am reading a file wit 1 very long line of text (the line consists of multiple records with no cr/lf). What I would like to do is...
5
by: Ben | last post by:
I'm currently trying to develop a demonstrator in python for an ontology of a football team. At present all the fit players are exported to a text document. The program reads the document in and...
3
by: danpres2k | last post by:
Hello, I have a file with email address at a lot of junk data. I want to get the email addresses out of that file so that each email address is stored at a new line. I am trying to do...
2
by: CV | last post by:
How can I match 'n' number of neighbouring words of a pattern using regular expressions? For example, suppose I am looking for the pattern "length xyz cm" in some text. where xyz is a number -...
8
by: Natti | last post by:
Hello, I have a perl program which parses an input file for specific error patterns and generates an output file with all these lines. One of the error patterns that I am looking at spans across...
0
by: rohitkec | last post by:
I have tried the following code: #! /usr/bin/perl use Switch; $i=0; open(FILE,"$ARGV") || die "cannot open file"; @lines = <FILE>; close(FILE); open(wfile,">$ARGV");
1
by: arunbs84 | last post by:
hi friends this is arun from coimbatore.i had written one program for pattern matching.That is ,the user have one file and after run his c program he pass some text command line, if the text is found...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.