Hello,
I wanted to know if there is any way by using regular expression to count the occurrences of a repeating pattern in a line ?
here is the problem statement
Given a log file:
some garbage...from:123.54,78.21...more garbage..to:56,82,124.54...more some more garbage...from:11.54,45.84...garbage..to:115.87,98.65 ... Assumption: these coordinates will always appear in sequence: from ... to... from ... to... But these from - to pair may or may not be on same line
Write a script to return pairs of (from, to) coordinates.
The only way I could think of was by splitting the line....But I feel there should be a better way. here is my code below
#!/usr/bin/perl use Data::Dumper; open(FH,"<abc.txt")or die EXPR; while (<FH>) { my @words = split(/ /,$_); foreach (@words) { if ($_=~/from:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) { print "$1- \n"; }elsif ($_ =~/to:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/){ print "$1 \n"; } } } close (FH);
This is the sample input file abc.txt
hshhhgljlkjglgkjj from:198.18.66.5 aegighighighilg to:198.18.66.6 iiuf +duifuiuih from:198.18.66.7 hiihhj to:198.18.66.8 hhouhoho from:198.18.66.9 igilgojhjh to:198.18.6 +6.10 igighliho from:198.18.66.11 highighioouhouhhhoh to:198.18.66.12
And the output I am expecting is
198.18.66.5 ,198.18.66.6 198.18.66.7 ,198.18.66.8 198.18.66.9 ,198.18.66.10 198.18.66.11 ,198.18.66.12

In reply to To find and count a repeating pattern in a line by punitpawar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.