2011-09-06 127 views
1

我尝试用Perl使用grep,但我必须recive从Perl的参数使用grep选择用它们,我这样做如何从perl脚本参数传递给bash脚本

#!/usr/bin/perl 
system(grep -c $ARGV[0] $ARGV[1]); 

,这将引发一个错误,这怎么可以实施?

+1

'别名grepc = 'grep的-c $ @'''在.bashrc' – ikegami

回答

7
system('grep', '-c', $ARGV[0], $ARGV[1]); 

但请考虑这是否是你想要做的。 Perl可以在不调用外部程序的情况下自行完成很多事情。

+1

见http://stackoverflow.com/questions/3477916/using-perls-system/3478060#3478060进行错误处理。 – daxim

0

system()的参数必须是字符串(或字符串列表)。请尝试:

#!/usr/bin/perl 
system("grep -c $ARGV[0] $ARGV[1]"); 
+2

列表形式更安全。考虑有人用''的第一个参数调用你的脚本的可能性; rm -rf $ HOME''。这不是真正的问题,除非脚本以额外的权限运行(用户可以直接运行'rm -rf $ HOME'),但值得考虑。如果您需要调用shell为您执行命令,则单字符串表单很有用;例如'system(“command1 | command2”)'*可以在Perl中完成,但是它有很多工作。 'perldoc -f系统' –

+1

它也失败了像'script.pl“这样简单的东西不能”文件“ – ikegami

0

您可能不会从该代码中得到您所期望的。从perldoc -f system

The return value is the exit status of the program as returned by 
the "wait" call. 

system实际上不会给你数从grep,刚刚从grep的过程的返回值。

要能够使用perl中的值,请使用qx()或反引号。例如。

my $count = `grep -c ... `; 
# or 
my $count2 = qx(grep -c ...); 

请注意,这会在数字后出现换行符,例如: “6 \ n” 个。

但是,为什么不使用所有perl?

my $search = shift; 
my $count; 
/$search/ and $count++ while (<>); 
say "Count is $count"; 

由钻石操作<>执行可以在不法分子手中的危险,但隐含open。你不是可以手动打开文件用三个参数的open:

use autodie; 
my ($search, $file) = @ARGV; 
my $count; 
open my $fh, '<', $file; 
/$search/ and $count++ while (<$fh>); 
say "Count is $count";