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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to extract matching data from line

Status
Not open for further replies.

abc73

Programmer
Apr 28, 2004
89
US
Hi,
I am new to perl. I am trying to read a text file and extract a match some data in each line and store it in an array. I can read the file but having trouble to extract the data from eachline. i.e. line looks like:

Code:
test1 testing 6758 d:\something\te##skfj.com
I want to extract range of data starting from d: all the way to ## in one variable and data starting from ## to the end in second variable.

Can someone help in building an appropriate regular expression. After d:\ I can have diffrent value on eachline of the file and same for ## after that I can have any value.

Thanks
 
How about:
tt]
$line=~/d:(.*)##(.*)/;
$var1=$1;
$var2=$2;
[/tt]
Now it's over to cntr for an awk solution.
 
Sorry, that should have been:

How about:
[tt]
$line=~/d:(.*)##(.*)/;
$var1=$1;
$var2=$2;
[/tt]
Now it's over to cntr for an awk solution.
 
I don't mind if I do.
Code:
BEGIN{FS="d:|##"}
{print $2,$3}

 
but it's printing the following:

$var1 = :\something\te##
$var2 = \something\te

As I am looking something like below:
Code:
$var1 = d:\something\te
$var2 = ##skfj.com
 
[tt]
$line=~/(d:.*)(##.*)/;
$var1=$1;
$var2=$2;
[/tt]
Sorry, Tony.
 
Now it doesn't print anything. Can someone help please.
 
That last post of mine was in response to cntr's post.

That solution should work, assuming your lines really do have "d:" and "##" in them, in that order.
 
Yes you right it works. Then probably I am doing something wrong. Actually I am reading this from a file. My text file contains lines that I need to extract the data. Here is what I am doing:

Code:
open (FPTR,$fileName) || die "Can't Open File: $fileName\n";
while (<FPTR>)  # While still input lines in the file...
{
   $line=$_;
   $line=~/(d:.*)(##.*)/;
   $var1=$1;
   $var2=$2;
   print $var1."\n";
   print $var2."\n\n";
}
[\code]

Can you please help what I am doing wrong and why can't I get the data.

Thanks
 
Using your data and code, I get the following output:
[tt]
d:\something\te
##skfj.com
[/tt]
Is that not what's wanted?
 
Code seems to assign to a lot of unneccesary variables. It can be reduced to
Code:
use strict;
use warnings;

while (<DATA>) {
    chomp;              # remove linefeed
    /(d:.*)(##.*)/;
    print "$1\n$2\n\n";
}
__DATA__
test1 testing 6758 d:\something\te##skfj.com
any other rubbish 1234 d:\path\xx##url
 
Thanks all it was my mistake. I got it. Thanks again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top