A
A
Andrey Bondarchuk2014-12-17 09:29:05
Perl
Andrey Bondarchuk, 2014-12-17 09:29:05

Perl how to print the first number in a string?

By examples, I roughly figured out how to teach a script to telnet to a piece of iron, execute the required commands and log them. Now I need to display the first number of the last line from the log into a separate document.
I found something similar in the example and substituted my data

$s = "nnn MAC address learned in routing instance PPPoE-xxx bridge domain __PPPoE-xxxx__";
if ($s =~ /(\d)(?=\s)/)  # Найти цифру за которой стоит '\s'(пробел)
    {
        print "$1\n"; 
   }
else { print "ошибка поиска\n";}

Only here it is not indicated that you need to find exactly the first number after which there is a space. What identifier will point exactly to the first match? Or maybe you shouldn’t bother, because in the required line only nnn is an integer (xxx can be a combination of letters and numbers)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
ldv, 2014-12-17
@ldvldv

upd:

#!/usr/bin/perl
use strict;
use warnings;
 
open(my $file, 'log.txt') or die "Could not open file $!";


my $first = <$file>;

if ($first =~ /^(\d+)(?=\s)/)  
{
   print "$1\n"; 
}
else { print "ошибка поиска\n";}

I
Ilya Evseev, 2014-12-17
@IlyaEvseev

What identifier will point exactly to the first match?

None, this is a property of the pattern search operation.
$s = "...";
my @lines = split /[\r\n]+/, $s;
my $result = ( $lines[$#lines] =~ /(\d)\s/ ? $1 : "not found" );
print "$result\n";

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question