How to extract string from raw data file (stuck)

140 Views Asked by At

I have a raw data text file and I am writing a perl script to extract a string from it. I am trying to get the computer name where the result would only be UFLEX-06 however, I am getting Computer Name: UFLEX-06 (with the tab spacing at the back of Computer Name).

This is what the text file contains:

Computer Info: Computer Name: UFLEX-06 Computer is external to Teradyne. Computer IP Address(es):

This is what I've done so far in my perl script:

use strict;
use warnings;

my $filename = 'IGXLEventLog.3.17.2015.20.25.12.625.log';
open(my $fn, '<', $filename) or die "Could not open file '$filename' $!";

our %details;

while(my $row = <$fn>)
{
    chomp $row;

    if($row =~ /Computer Name:/i)
    {
        my $cp_line;
        do
        {
            $cp_line .= $row;
        }while($row !~ /Computer Name:/);

    #Remove
    $cp_line =~ /Computer Name:/s;

    my @String = split(/Computer Name:/, $cp_line);

    #Assigning array elements to hash array
    $details{cp_line} = $String[0];

    print $details{cp_line};
    }
}

I'm new to Perl so do pardon me if there are any obvious mistakes. My idea was to use split so that I can remove the Computer Name:. Any help on this?

2

There are 2 best solutions below

3
On BEST ANSWER

I really don't follow what you are trying to do with your own code, but this is all that is necessary

use strict;
use warnings;

my $filename = 'IGXLEventLog.3.17.2015.20.25.12.625.log';

open my $fh, '<', $filename or die "Could not open file '$filename': $!";

while ( <$fh> ) {
    if ( /Computer Name:\s*(\S+)/i ) {
        print $1, "\n";
    }
}
1
On

You can use a regex with capturing groups like this:

Computer Name: (.*)

And then grab the content from the group

Working demo

I'm not good at Perl but I think you can use below code and adapt it to your needs:

use strict;
use warnings;

my $filename = 'IGXLEventLog.3.17.2015.20.25.12.625.log';
open(my $fn, '<', $filename) or die "Could not open file '$filename' $!";

our %details;

while(my $row = <$fn>)
{
    chomp $row;

    if($row =~ m/Computer Name: (.*)/)
    {   
         print $1;
    }
}