我试图使用通常的backticks从perl脚本中运行tail命令。
我的perl脚本中的部分如下:
$nexusTime += nexusUploadTime(`tail $log -n 5`);因此,我正在尝试获取该文件的最后5行,但是当perl脚本完成时,我会得到以下错误:
sh: line 1: -n: command not found尽管当我在命令行上运行命令时,它确实是成功的,我可以从这个特定的位置看到这5行。
不知道这是怎么回事。为什么它在命令行中工作,但是通过perl它不会识别-n选项。
有人有什么建议吗?
发布于 2015-03-25 22:03:24
$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`);发布于 2015-03-25 22:11:34
ikegami pointed out您的错误,但我建议尽量避免外部命令。它们是不可移植的,调试它们可能是一件痛苦的事情。您可以使用以下纯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实用程序所得到的结果。
发布于 2015-03-25 21:49:50
这个问题的答案是将选项-n 5放在目标文件之前。
https://stackoverflow.com/questions/29267050
复制相似问题