473,748 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Match pattern and Extract section from file

23 New Member
Hi All
Today only i joined this group. need ur help.
Here goes my question:

Is there any simple way to match for a particular pattern ( with start and end delimitters) and extract the matched section?

I am doing it reading the contents line by line and setting the flags. But this logic is becoming complex, as i need to match and extract based on certain conditions.

for ex:

#ifdef X
some code
#endif

#ifdef Y
somecode
#ifdef Z
somemorecode
#else
code that does not match condition
#endif
#endif

---------------------------------
from the above text, i have to extract sections between #ifdef and #endif.( and ofcourse #else in some cases)

let me know for any further explanation about the same.

thanks in adv
Pramod
Nov 23 '07 #1
6 4498
numberwhun
3,509 Recognized Expert Moderator Specialist
Hi All
Today only i joined this group. need ur help.
Here goes my question:

Is there any simple way to match for a particular pattern ( with start and end delimitters) and extract the matched section?

I am doing it reading the contents line by line and setting the flags. But this logic is becoming complex, as i need to match and extract based on certain conditions.

for ex:

#ifdef X
some code
#endif

#ifdef Y
somecode
#ifdef Z
somemorecode
#else
code that does not match condition
#endif
#endif

---------------------------------
from the above text, i have to extract sections between #ifdef and #endif.( and ofcourse #else in some cases)

let me know for any further explanation about the same.

thanks in adv
Pramod
Well, considering this is a learning forum and not a script writing service, I am obligated to ask you what you have tried thus far.

Please post your code that you have tried, in the necessary code tags, and we will help guide you from there.

Regards,

Jeff
Nov 23 '07 #2
eggi
9 New Member
To get you started, you can extract elements from a perl match using parentheses on the left hand side and $ variables on the right

for instance

Expand|Select|Wrap|Line Numbers
  1. $string="what is it"
  2. print "$string\n";
  3. $string =~ /^.* (is) .*$/$1/;
  4. print "$string\n";
  5.  
first print should get you "what is it"
second print should just be "is"

Hope this helps get you started!

, Mike
Nov 25 '07 #3
pramodkh
23 New Member
Here is what i hav tried so far.

1. Get the C file contents into array
2. Read elements of array(i.e lines of file)
3. check if it matches with '#ifdef and #endif'
4. set the flags( ifdefflag and endifflag)
5. take actions accordingly ( i mean write contents of ifdef into a temp file excluding #ifedf and #endif)

This is becoming complex to include all conditions like ( to check for #else and nested #ifdef )

Let me know is there any simple solution to achieve this. flag setting doesnt seem to be so useful in some cases.

Thanks
Pramod
Nov 27 '07 #4
numberwhun
3,509 Recognized Expert Moderator Specialist
The pseudo code that you supplied is not your actual code. Please provide your code, surrounded by the necessary code tags, and we will try and help you.

Regards,

Jeff
Nov 27 '07 #5
pramodkh
23 New Member
Hi,

Here is the code...need to format and change some of the declarations.
let me know if you need anu further comments to understand the code.

Expand|Select|Wrap|Line Numbers
  1. # Global variable Declaration and  Initialization
  2. my $ifdefflag = 0;
  3. my $elseflag = 0;
  4. my $endifflag = 0;
  5. my $counter = 0;
  6. my $flag=0;
  7. my $ctrToLookForifdef = 0;
  8. my @filecontents;
  9. my @splititem;
  10. my @compiler_switches =(A,B,C); #has list of compiler switches used with #ifdef
  11.  
  12. #### Open File for reading the contents
  13. open FH, "source.c" or die "can not open source.c...$!";
  14. while (<FH>) {
  15.                @filecontents = <FH>;
  16. }
  17. #### Backing up source file using system command
  18. `copy source.c source.bak`;
  19. #### Create new file after refactoring
  20. open NEWFH, ">source.c" or die "can not open source.c...$!";
  21.  
  22. ### Read contents of array, Match for ifdef and set the flags
  23. foreach my $item (@filecontents ){
  24.                # Match for #ifdef tag and set the flag
  25.     if($item =~m/#ifdef/) {    
  26.         $endifflag = 0;
  27.                                  # couter to track nested ifdef    
  28.         $ctrToLookForifdef++;        
  29.                                  ## splitting with space to check for valid compiler switch
  30.         @splititem= split(" ", $item);
  31.         foreach my $cs (@compiler_switches){
  32.             chomp $cs;
  33.             chomp $splititem[1];
  34.             if( $splititem[1] eq $cs and ($ctrToLookForifdef == 1)){
  35.                 $ifdefflag = 1;
  36.                 $flag=0;
  37.                 last;
  38.             }
  39.             else {                
  40.                 $flag=1;
  41.             }
  42.         }
  43.         next;
  44.     }
  45.     elsif( $item =~m/#endif/){    
  46.         $ctrToLookForifdef--;
  47.         if($ctrToLookForifdef == 0){
  48.             $endifflag = 1;
  49.             $ifdefflag = 0;
  50.             $flag=0;
  51.         }
  52.         next;
  53.     }
  54.     else {
  55.         if($flag==1){
  56.             next;
  57.         }        
  58.         print NEWFH "$item";    
  59.         next;
  60.     }
  61.     if($ifdefflag and $endifflag==0){
  62.         print NEWFH "$item";    
  63.     }
  64.     if($elseflag and $flag){
  65.         print NEWFH "$item";            
  66.     }
  67.     if($endifflag){
  68.         $ifdefflag = 0;
  69.         next;
  70.     }
  71. }
  72. close FH;
  73. close NEWFH;
  74. ###### end of the file
  75.  
Regards
Pramod
Nov 28 '07 #6
pramodkh
23 New Member
Hi All,

Any updates on this post? let me know if you need any further details.
I am still waiting for replies.

Regards
Pramod
Dec 6 '07 #7

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

Similar topics

20
5772
by: Ravi | last post by:
Hi, I have about 200GB of data that I need to go through and extract the common first part of a line. Something like this. >>>a = "abcdefghijklmnopqrstuvwxyz" >>>b = "abcdefghijklmnopBHLHT" >>>c = extract(a,b) >>>print c "abcdefghijklmnop"
0
1946
by: Follower | last post by:
Hi, I am working on a function to return extracts from a text document with a specific phrase highlighted (i.e. display the context of the matched phrase). The requirements are: * Match should be case-insensitive, but extract should have case preserved.
6
2324
by: Matt Wette | last post by:
Over the last few years I have converted from Perl and Scheme to Python. There one task that I do often that is really slick in Perl but escapes me in Python. I read in a text line from a file and check it against several regular expressions and do something once I find a match. For example, in perl ... if ($line =~ /struct {/) { do something } elsif ($line =~ /typedef struct {/) { do something else
2
2137
by: cricfan | last post by:
I'm parsing a text file to extract word definitions. For example the input text file contains the following content: di.va.gate \'di_--v*-.ga_-t\ vb pas.sim \'pas-*m\ adv : here and there : THROUGHOUT I am trying to obtain words between two literal backslashes (\ .. \). I am not able to match words between two literal backslashes using the regxp - re.compile(r'\\*\\').
3
1785
by: David Moore | last post by:
Hi All, I expect someone can crack this one in no time. Ok, what I'd like to do is to match a pattern in a string and extract a portion of it. For example if I had a string like: 'The store had apples(20) and pears(30)' how do I extract the '20' and '30'? ie. if the pattern is 'apples(??)', how do I expect the '??'.
8
10289
by: sherifffruitfly | last post by:
Hi, I've been searching as best I can for this - coming up with little. I have a file that is full of lines fitting this pattern: (?<year>\d{4}),(?<amount>\d{6,7}) I'm likely to get a bunch of hits with this - I'm only interested in the *last* one. Is there a way to build the concept "last" into the
10
2946
by: wo_shi_big_stomach | last post by:
Newbie to python writing a script to recurse a directory tree and delete the first line of a file if it contains a given string. I get the same error on a Mac running OS X 10.4.8 and FreeBSD 6.1. Here's the script: # start of program # p.pl - fix broken SMTP headers in email files #
6
1780
by: hari.siri74 | last post by:
Extract the application name with version from an RPM string like hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- Linux.RPM.
1
5063
by: manishabh77 | last post by:
I will be obliged if anybody can help me with this problem: I am trying to extract data from an excel sheet that matches IDs given in column 4 of the excel sheet.I have stored those query IDs in an array (@names). After I look for the match in this section of the code: if ($value=~/^$names$/), I want to write out only those rows that satisfy the above natch condition. But currently the code I have here writes out everything. How do I get it to...
0
9552
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.