• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 205
  • Last Modified:

perl search and print regular expression

file1 contains:
rownum   id             gender  names
---      --------       ----    -----
<1> <1.2.3.4.5.0.0>    <male>  <john>
<1> <1.2.3.4.5.0.3>    <male>  <joe>
<1> <1.2.3.4.5.0.9>    <male>  <mary>


I want the result to store in file2 as:
john 0
joe 3
mary 9


file2 should have two columns:
column 1 is name without <>
column 2 the last digit of the id


can someone help me write this in perl?
I spend about one hour and could not get it to work.

thanks in advance

0
aauser
Asked:
aauser
  • 4
1 Solution
 
TintinCommented:
#!/usr/bin/perl
use strict;

open FILE1, "file1.txt" or die "Can not open file1.txt $!\n";
open FILE2, ">file2.txt" or die "Can not open file2.txt $!\n";

while (<FILE1>) {
  chomp;
  next unless (/</);
  my ($id,$name) = /<\d+>\s+<\S+(\d+)>\s+<\w+>\s+<(\w+)>/;
  print FILE2 "$name $id\n";
}

close FILE1;
close FILE2;
0
 
OKSDCommented:
Hmm... won't that erase file2.txt each time the program is run? If you want to update suff often, that could be a problem, what about useing ">>file2.txt"?

OKSD
0
 
aauserAuthor Commented:
excellent job- thanks.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
aauserAuthor Commented:
if I have /tim under the name column, it does not
print /tim.  How can I fix this?  thanks
0
 
aauserAuthor Commented:
the last line under name is /
I need to print this too.
so file2.txt would look something like:

john 0
joe 3
mary 9
.
.
/tim 8
/ 0




0
 
aauserAuthor Commented:
forget it.
I got it to work.  I don't need to display /tim.
just tim is ok.

thanks
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now