【问题标题】:Executing grep via Perl通过 Perl 执行 grep
【发布时间】:2014-01-14 17:26:01
【问题描述】:

我是 Perl 的新手。我正在尝试用 perl 执行 grep 命令。

我必须从文件中读取输入,并根据输入执行 grep。

我的代码如下:

#!/usr/bin/perl
use warnings;
use strict;

#Reading input files line by line
open FILE, "input.txt" or die $!;
my $lineno = 1;
while (<FILE>) {

        print " $_";
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh  > out.txt`;
        print $result

}
print "************************************************************\n";

但是,如果我运行脚本,它看起来像一个无限循环,脚本一直在等待,out.txt 文件中没有打印任何内容。

【问题讨论】:

  • 所有grep 输出都进入out.txt,而不是$result
  • Perl 有一个非常好的内置 grep 函数,你为什么还要使用 grep 命令?
  • 您是否希望 Satheesh 成为模式,而 $_ 成为要搜索的目录?如果是这样,我认为你有那些倒退。

标签: perl file-io grep line-by-line


【解决方案1】:

挂起的原因是您在阅读FILE 后忘记使用chomp。所以$_的末尾有一个换行符,它正在执行两个shell命令:

grep -r $_
Satheesh > out.txt

由于grep 没有文件名参数,它从标准输入读取,即终端。如果您在挂起时键入 Ctl-d,则会收到一条错误消息,告诉您没有 Satheesh 命令。

此外,由于您将grep 的输出重定向到out.txt,因此$result 中没有任何内容。如果你想在一个变量中捕获输出并将其放入文件中,你可以使用tee 命令。

解决方法如下:

while (<FILE>) {

        print " $_";
        chomp;
        #This is what expected.
        #our $result=`grep -r Unable Satheesh  > out.txt`;
        our $result=`grep -r $_ Satheesh | tee out.txt`;
        print $result

}

【讨论】:

    猜你喜欢
    • 2015-10-30
    • 2017-07-21
    • 2021-06-18
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 2012-05-18
    相关资源
    最近更新 更多