簡體   English   中英

perl反引號中使用的尾部命令

[英]Tail command used in perl backticks

我正在嘗試使用通常的反引號在perl腳本中運行tail命令。

我的perl腳本中的部分如下:

$nexusTime += nexusUploadTime(`tail $log -n 5`);

所以我試圖獲取此文件的最后5行,但是當perl腳本完成時我收到以下錯誤:

sh: line 1: -n: command not found

即使我在命令行上運行命令它確實成功,我可以看到該特定的5行。

不知道這里發生了什么。 為什么它從命令行工作,但通過perl它將無法識別-n選項。

有人有什么建議嗎?

$log有一個無關的尾隨換行符,因此您正在執行

tail file.log
 -n 5            # Tries to execute a program named "-n"

固定:

chomp($log);

請注意,如果log $log包含shell元字符(例如空格),則會遇到問題。 固定:

use String::ShellQuote qw( shell_quote );

my $tail_cmd = shell_quote('tail', '-n', '5', '--', $log);
$nexusTime += nexusUploadTime(`$tail_cmd`);

ikegami指出了你的錯誤,但我建議盡可能避免使用外部命令。 它們不可移植,調試它們可能是一件痛苦的事情。 您可以使用純Perl代碼模擬tail ,如下所示:

use strict;
use warnings;

use File::ReadBackwards;

sub tail {
    my ($file, $num_lines) = @_;

    my $bw = File::ReadBackwards->new($file) or die "Can't read '$file': $!";

    my ($lines, $count);
    while (defined(my $line = $bw->readline) && $num_lines > $count++) {
        $lines .= $line;
    }

    $bw->close;

    return $lines;
}

print tail('/usr/share/dict/words', 5);

產量

ZZZ
zZt
Zz
ZZ
zyzzyvas

請注意,如果傳遞包含換行符的文件名,則會失敗

Can't read 'foo
': No such file or directory at tail.pl line 10.

而不是更神秘

sh: line 1: -n: command not found

你是通過在反引號中運行tail實用程序得到的。

這個問題的答案是在目標文件之前放置選項-n 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM