×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!
  • Students Click Here

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

Jobs

Print texts between and

Print texts between and

Print texts between and

(OP)
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

RE: Print texts between and

Hi

Supposing the input data is in variable $data, this will populate the array @match with the matches :

CODE --> Perl

@match=$data=~m,<source>(.*?)</source>,gs; 

Feherke.
http://feherke.github.com/

RE: Print texts between and

(OP)
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 ?

RE: Print texts between and

Hi

Well, putting your original post's text into a file Per9922.txt, running this :

CODE --> command-line

perl -0ne '@m=$_=~m,<source>(.*?)</source>,gs;print">>$_<<\n\n"for@m' Per9922.txt 
Will output :

CODE --> output

>> and <<

>> and <<

>>Test<<

>>Test1
av test1<<

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

Feherke.
http://feherke.github.com/

RE: Print texts between and

(OP)
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;

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close