[英]Output from bash command not storing in array
my below code is very simple... all im doing is grepping a file using an IP address REGEX, and any IP addresses that are found that match my REGEX, I want to store them in @array2. 我下面的代码非常简单...我所要做的就是使用IP地址REGEX来查找文件,找到的任何与我的REGEX匹配的IP地址都想存储在@ array2中。
i know my REGEX works, because ive tested it on a linux command line and it works exactly how I want, but when its integrated into the script, it just returns blank. 我知道我的REGEX可以工作,因为ive在linux命令行上对其进行了测试,并且它的工作方式完全符合我的要求,但是当它集成到脚本中时,它只会返回空白。 there should be 700 IP's stored in the array.
阵列中应存储700个IP。
#!/usr/bin/perl
use warnings;
use strict;
my @array2 = `grep -Eo "\"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\"" test1.txt`;
print @array2;
Backticks ``
behave like a double quoted string by default. 反引号
``
默认情况下就像双引号字符串一样。
Therefore you need to escape your backslashes: 因此,您需要转义反斜杠:
my @array2 = `grep -Eo "\\"\\b[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\"" test1.txt`;
Alternatively, you can use a single quoted version of qx
to avoid any interpolation: 另外,您可以使用单引号的
qx
以避免任何插值:
my @array2 = qx'grep -Eo "\"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\"" test1.txt';
However, the method I'd recommend is to not shell out at all, but instead do this logic in perl: 但是,我建议的方法是完全不使用Shell,而是在perl中执行以下逻辑:
my @array2 = do {
open my $fh, '<', 'test1.txt' or die "Can't open file: $!";
grep /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b/, <$fh>;
};
I really wouldn't mix bash and perl. 我真的不会混合bash和perl。 It's just asking for pain.
它只是在寻求痛苦。 Perl can do it all natively.
Perl可以原生完成所有操作。
Something like: 就像是:
open (my $input_fh, "<", "test.txt" ) or die $!;
my @results = grep ( /\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/, <$input_fh> );
This does however, require slurping the file into memory, which isn't optimal - I'd generally use a while
loop, instead. 但是,这确实需要将文件拖到内存中,这不是最佳选择-我通常会使用
while
循环。
The text inside the backticks undergoes double-quotish substitution. 反引号内的文本经过双引号替换。 You will need to double your backslashes.
您需要将反斜杠加倍。
Running grep
from inside Perl is dubious, anyway; 无论如何,从Perl内部运行
grep
是可疑的。 just slurp in the text file and use Perl to find the matches. 只需将其插入文本文件并使用Perl查找匹配项即可。
The easiest way to retrieve the output from an external command is to use open(): 从外部命令检索输出的最简单方法是使用open():
open(FH, 'grep -Eo \"\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\" test1.txt'."|")
my @array2=<FH>;
close (FH);
..though I think Sobrique's idea is the best answer here. ..尽管我认为Sobrique的想法是这里的最佳答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.