在Perl中,与Shell脚本中grep命令相当的命令是什么?

3

我在shell脚本中使用以下语法-

imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall | grep "Black Scholes " | cut-d"=" -f2

如果有一个可执行文件imp_vol,它会输出一些内容。那么在Perl脚本中,它将对应什么呢?例如:

imp_vol -u 110.5 -s 110.9 -p 0.005 -t 0.041 -c 1
    Underlying Price = 110.5
    Strike Price = 110.9
    Price = 0.005
    Time = 0.041
    IsCall = 1
    Black Scholes Vol = 0.0108141

我的目的是在这种情况下获取Black Scholes Vol的值,例如为`.0108141`,并将其存储在某个变量中,因为我需要再次将该变量传递给某个函数。

非常感谢您的帮助。

4个回答

2

Perl 中实际上有一个 grep 函数。它将表达式或块作为第一个参数,字符串列表作为第二个参数。因此,您可以这样做:

my @list = grep(/abcd/, (<>));

另请参见:grep - perldoc.perl.org

在您的特定情况下,您可以使用块形式来提取价格,如下所示:

imp_vol | perl -e 'print grep { s/\s+Black Scholes Vol = ([-+]?[0-9]*\.?[0-9]+)/$1/ } (<>)'

1
如果您想让所有类似于“Black Scholes”的内容与您的grep匹配
imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall | perl -ne 'print $1 if $_ =~ /Black Scholes .* = (\d+(?:\.\d+)?)/;'

"Black Scholes Vol" 精确地。
| perl -ne 'print $1 if $_ =~ /Black Scholes Vol = (\d+(?:\.\d+)?)/;'

0

使用正则表达式

while (<>) {
    next if !/abcd/;
    # ...
}

此外,要替换cut,请使用捕获组,但我无法提供更多代码,因为我不知道您的数据格式。

0

要执行该命令,您可以使用open获取文件句柄,从中读取其输出。然后,您可以使用单个正则表达式来匹配行并提取值。例如:

my $cmd = "imp_vol -u $undr_price -s $str_price -p $price -t $mat -c $iscall";
open (my $imp, '-|', $cmd) or die "Couldn't execute command: $!";

my $extracted;
while (<$imp>) {
    if (/Black Scholes Vol = (.*)/) {
        $extracted = $1;
    }
}
close $imp;

圆括号创建了一个捕获组,它将值提取到特殊的$1变量中。

如果您能够将输入导入管道而不必在Perl中执行命令,则以下一行代码就足够了:

imp_vol ... | perl -ne 'print $1 if /Black Scholes Vol = (.*)/'

@RobEarl-在当前情况下的使用怎么样? - Micheal_Sam
你可以在Perl脚本内执行该命令,也可以将其输出导入到脚本中。 - RobEarl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接