简体   繁体   English

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

[英]Tail command used in perl backticks

I'm trying to run a tail command from within a perl script using the usual backticks. 我正在尝试使用通常的反引号在perl脚本中运行tail命令。

The section in my perl script is as follows: 我的perl脚本中的部分如下:

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

So I'm trying to get the last 5 lines of this file but I'm getting the following error when the perl script finishes: 所以我试图获取此文件的最后5行,但是当perl脚本完成时我收到以下错误:

sh: line 1: -n: command not found

Even though when I run the command on the command line it is indeed successful and I can see the 5 lines from that particular. 即使我在命令行上运行命令它确实成功,我可以看到该特定的5行。

Not sure what is going on here. 不知道这里发生了什么。 Why it works from command line but through perl it won't recognize the -n option. 为什么它从命令行工作,但通过perl它将无法识别-n选项。

Anybody have any suggestions? 有人有什么建议吗?

$log has an extraneous trailing newline, so you are executing $log有一个无关的尾随换行符,因此您正在执行

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

Fix: 固定:

chomp($log);

Note that you will run into problems if log $log contains shell meta characters (such as spaces). 请注意,如果log $log包含shell元字符(例如空格),则会遇到问题。 Fix: 固定:

use String::ShellQuote qw( shell_quote );

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

ikegami pointed out your error, but I would recommend avoiding external commands whenever possible. ikegami指出了你的错误,但我建议尽可能避免使用外部命令。 They aren't portable and debugging them can be a pain, among other things. 它们不可移植,调试它们可能是一件痛苦的事情。 You can simulate tail with pure Perl code like this: 您可以使用纯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);

Output 产量

ZZZ
zZt
Zz
ZZ
zyzzyvas

Note that if you pass a file name containing a newline, this will fail with 请注意,如果传递包含换行符的文件名,则会失败

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

instead of the more cryptic 而不是更神秘

sh: line 1: -n: command not found

that you got from running the tail utility in backticks. 你是通过在反引号中运行tail实用程序得到的。

这个问题的答案是在目标文件之前放置选项-n 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM