[英]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.