在 perl 中使用 bash 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6026984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using bash command in perl
提问by ibrahim
i have short bash code
我有简短的 bash 代码
cat example.txt | grep mail | awk -F, '{print }' | awk -F= '{print }'
I want to use it in perl script, and put its output to an array line by line. I tried this but did not work
我想在 perl 脚本中使用它,并将其输出逐行放入数组。我试过这个但没有用
@array = system('cat /path/example.txt | grep mail | awk -F, {print } | awk -F= {print }');
Thanks for helping...
谢谢你的帮助...
回答by Rafe Kettler
The return value of system()
is the return status of the command you executed. If you want the output, use backticks:
的返回值system()
是您执行的命令的返回状态。如果需要输出,请使用反引号:
@array = `cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}`;
When evaluated in list context (e.g. when the return value is assigned to an array), you'll get the lines of output (or an empty list if there's no output).
在列表上下文中评估时(例如,当返回值分配给数组时),您将获得输出行(如果没有输出,则为空列表)。
回答by ADW
Try:
尝试:
@array = `cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}')`;
Noting that backticks are used and that the dollar signs need to be escaped as the qx operator will interpolate by default (i.e. it will think that $1 are Perl variables rather than arguments to awk).
注意使用反引号并且美元符号需要转义,因为 qx 运算符将默认插入(即它会认为 $1 是 Perl 变量而不是 awk 的参数)。
回答by TLP
Couldn't help making a pure perl version... should work the same, if I remember my very scant awk correctly.
忍不住制作了一个纯 perl 版本...应该可以正常工作,如果我正确地记得我很少的 awk。
use strict;
use warnings;
open A, '<', '/path/example.txt' or die $!;
my @array = map { (split(/=/,(split(/,/,$_))[0]))[1] . "\n" } (grep /mail/, <A>);