473,386 Members | 1,644 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 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 5018
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.