Regex help - need flexibility to parse with or without blanks in output....

T

tudmuf2b

Perl Gurus:

I'm trying to write a script that runs the rup command, and then takes
the output of it to do something.

Here are 2 possible outputs that rup could give you (if a box has been
up for less than a day, there is no "xx days" field):


bastion1 up 18:01, load average: 0.17 0.15 0.06
bastion2 up 30 days, 22:34, load average: 0.00 0.00 0.02


My script works for the 2nd case (the "bastion2" host) - even if "days"
is singular. But how do I make my regex more flexible so that it can
say:

1. if the box has been up for less than a day, then just skip to the
time field and grab it, so that $days=0, $time=18:01 (from the example
above).

2. if the box has been up for X days, then I want to grab the number of
days so that $days=30, and also grab the time, so that $time=22:34
(above).

Somehow I need to say something like
/.*up\s+(\d+\s+days?,|.*\d{1,2}:\d+),/

but I want to grab $days no matter what:



#!/usr/bin/perl

use strict;
use warnings;
use Sys::Hostname;
use Time::parseDate;

my ($seconds,$days,$time);
my $host = hostname;
my $rup = `rup $host`;

chomp ($rup);

($days,$time) = $rup =~
m#\S+\s+up\s+(\d+)\s+days?,\s+(\d{1,2}:\d{2}),#;

print "days is $days\n";
print "time is $time\n";
 
G

Gunnar Hjalmarsson

Here are 2 possible outputs that rup could give you (if a box has been
up for less than a day, there is no "xx days" field):

bastion1 up 18:01, load average: 0.17 0.15 0.06
bastion2 up 30 days, 22:34, load average: 0.00 0.00 0.02

My script works for the 2nd case (the "bastion2" host) - even if "days"
is singular. But how do I make my regex more flexible so that it can
say:

1. if the box has been up for less than a day, then just skip to the
time field and grab it, so that $days=0, $time=18:01 (from the example
above).

2. if the box has been up for X days, then I want to grab the number of
days so that $days=30, and also grab the time, so that $time=22:34
(above).

($days,$time) = $rup =~
m#\S+\s+up\s+(\d+)\s+days?,\s+(\d{1,2}:\d{2}),#;

print "days is $days\n";

One way:

($days,$time) = $rup =~
m#\S+\s+up\s+(?:(\d+)\s+days,\s+)?(\d{1,2}:\d{2}),#;
print "days is " . ($days or 0) . "\n";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top