【问题标题】:grep command not showing any output in perlgrep 命令在 perl 中没有显示任何输出
【发布时间】:2021-08-17 14:22:41
【问题描述】:

我有一个数组@files,其中有多个.txt 文件。我正在尝试从这些文件中行的开头 grep 具有模式“/home/[a-z]+”的所有行。我正在尝试以下方法:

my @lines = grep (/^\/home\/[a-z]+/, @files);
chomp(@lines);
my @line = uniq(@lines);

但是当我尝试打印@lines 时,我没有在输出中得到任何东西。

谁能告诉我我在 grep 命令中做错了什么。谢谢。

【问题讨论】:

  • LIST 的参数 grep 不被解释为文件名列表。它被解释为搜索的文本项的LIST。换句话说,将LIST 视为您要搜索的文件中的行。 perldoc -f grep

标签: perl


【解决方案1】:

请查看以下代码示例,该示例演示了您选择的方法。

如果您提供内容示例@files 数组,将会非常有帮助。

注意:没有必要使用uniq(@lines),因为文件系统在其组织中假定 uniq 文件名

use strict;
use warnings;
use feature 'say';

my @files = <DATA>;
my @lines = grep( m!^/home/[a-z]+/!, @files);

say @lines;

__DATA__
/home/alex/work/samples
/home/philip/doc/asterix
/home/maria/bin/quick_search.c
/bin/grep
/sbin/test

输出

/home/alex/work/samples
/home/philip/doc/asterix
/home/maria/bin/quick_search.c

用于过滤存储在数组@files中的文件列表的匹配模式的示例代码。

use strict;
use warnings;
use feature 'say';

my @files = qw/abc.txt, bcd.txt, cde.txt/;
my @lines;

for my $file (@files) {
    my @temp;
    
    open my $fh, '<', $file
        or die "Couldn't open $file";
    @temp = grep( m!^/home/[a-z]+/!, <$fh>);    
    close $fh;
    
    @lines = (@lines, @temp);
}

chomp(@lines);

say for @lines;

【讨论】:

  • 感谢您的回复。 @files 包含文件 abc.txt、bcd.txt、cde.txt,我想从这些以 /home 开头的文件中提取行,例如 /home/john/abc /home/john/xyz 不幸的是,上述解决方案是不适合我。
  • 这个方案从__DATA__下面读取数据。调整代码以从您循环读取的一组文件中读取行应该不难。
  • 请根据提供的附加信息查看添加到我的答案中的示例代码。
  • 是的,该代码适用于所有具有 /home 但行中没有 ^ 选项的行:@temp = grep( m!^/home/[a-z]+/!, );当我使用 ^ 选项时,它不显示任何数据。
  • 您需要进一步调查,因为^ 表示begin of the string/line perlre
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 1970-01-01
  • 2021-12-01
  • 2014-06-23
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
相关资源
最近更新 更多