在Perl中打破qx / return

时间:2017-03-13 17:48:43

标签: perl command-line scripting

我有一个Ubuntu 16.04.1服务器,我搞砸了。目前,我正在使用它来监控我的互联网速度和连接。

我编写了一个脚本并使用Perl和crontab自动化它,但现在我想清理我的日志文件。

以下是执行Perl脚本时写入日志文件的内容:

Time: 12:40:01
Retrieving speedtest.net configuration...
Testing from TWC (now Spectrum) (123.45.67.890)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by Fibrant (Salisbury, NC) [60.95 km]: 51.184 ms
Testing download     speed................................................................................
Download: 37.76 Mbit/s
Testing upload speed....................................................................................................
Upload: 11.56 Mbit/s

我想要输出:

Download: 37.76 Mbit/s
Upload: 11.56 Mbit/s

我当前的Perl脚本如下所示:

    use strict;
    use warnings;

    my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime( time );
    my $nice_timestamp = sprintf( "%04d%02d%02d",   $year + 1900, $mon + 1, $mday );
    my $timer          = sprintf( "%02d:%02d:%02d", $hour,        $min,     $sec );
    my $filename = "/home/user/DailyLogs/InternetLog$nice_timestamp";

    open( my $fh, '>>', $filename ) or die "Could not open file '$filename' $!";

    my $output = qx"/home/user/.local/bin/speedtest-cli";

    print $fh "Time: ";
    print $fh $timer;
    print $fh "\n";
    print $fh $output;
    print $fh "\n\n";

    close $fh;

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:4)

您可以使用grep过滤qx输出:

my @output = grep {/^(Up|Down)load:/} qx"/home/user/.local/bin/speedtest-cli";
print $fh $_ for @output;

作为旁注,您可以使用POSIX简化$ timer代码:

use POSIX qw(strftime);
my @localtime = localtime;
my $nice_timestamp = strftime('%Y%m%d',   @localtime);
my $timer          = strftime('%H:%M:%S', @localtime);

答案 1 :(得分:0)

如果将结果分配给数组,

反引号(qx运算符)会将输出拆分为行。您可以使用grep选择要查看的行

我也会用 Time::Piece 模块生成时间和日期字符串

代码看起来像这样

use strict;
use warnings 'all';

use Time::Piece;

my $now = localtime;
$now->date_separator('');
my $nice_timestamp = $now->ymd; # Generates YYYYMMDD

my $filename = "/home/user/DailyLogs/InternetLog$nice_timestamp";

open my $fh, '>>', $filename or die qq{Unable to open file "$filename" for appending: $!};

my @output = qx</home/user/.local/bin/speedtest-cli>;

my $timer = $now->hms; # Generates HH:MM:SS

print $fh "Time: $timer\n";
print $fh for grep /^(?:Down|Up)load/, @output;
print $fh "\n\n";

close $fh;