Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print texts between <source> and </source> 1

Status
Not open for further replies.

Per9922

IS-IT--Management
Oct 1, 2004
74
0
0
SE
Hello,

I'm new to perl and I would like to extract text between to strings. I would like to print all texts between <source> and </source> in a text file. The <source> and </source> could be on different rows.

Ex1
====
<source>Test</source>

=> print Text

Ex2
====
<source>Test1
av test1</source>
<source>Test2</source>

=> Print Test1
av test1
Test2


Thanks
 
Hi

Supposing the input data is in variable $data, this will populate the array @match with the matches :
Perl:
[navy]@match[/navy][teal]=[/teal][navy]$data[/navy][teal]=~[/teal][b]m[/b][fuchsia],<source>(.*?)</source>,[/fuchsia][b]gs[/b][teal];[/teal]

Feherke.
[link feherke.github.com/][/url]
 
Thanks feherke!

If i have the data in a text file, how do I get the data into the data string ? How do I print @match ?
 
Hi

Well, putting your original post's text into a file Per9922.txt, running this :
Code:
perl -0ne '[navy]@m[/navy][teal]=[/teal][navy]$_[/navy][teal]=~[/teal][b]m[/b][fuchsia],<source>(.*?)</source>,[/fuchsia][b]gs[/b][teal];[/teal][b]print[/b][green][i]">>$_<<\n\n"[/i][/green][b]for[/b][navy]@m[/navy]' Per9922.txt
Will output :
Code:
>> and <<

>> and <<

>>Test<<

>>Test1
av test1<<

>>Test2<<
But better tell us more about the context.

Feherke.
[link feherke.github.com/][/url]
 
Thanks again! I have it working!

#!/usr/bin/perl
use strict;
use warnings;
my $filename = "test.txt";
my @match;

open my $fh, '<', $filename or die "error opening $filename: $!";
my $data = do { local $/; <$fh> };

@match=$data=~m,<source>(.*?)</source>,gs;
print "$_\n\n" for @match;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top