perl - Grep 匹配模式文件的所有行(perl -e 也可以)

标签 perl command-line grep

我正在寻找一种简单/优雅的方法来 grep 文件,以便每个返回的行都必须匹配模式文件的每一行。

带输入文件

acb
bc
ca
bac

和模式文件
a
b
c

命令应该返回
acb
bac

我试图用 grep -f 做到这一点但如果它匹配文件中的单个模式(而不是全部),则返回。我还尝试了递归调用 perl -ne 的方法。 (对于模式文件的每一行,在搜索文件上调用 perl -ne 并尝试 grep 到位)但我无法让语法解析器接受从 perl 对 perl 的调用,所以不确定这是否可能。

我认为可能有一种更优雅的方法来做到这一点,所以我想我会检查一下。谢谢!

===更新===

感谢您到目前为止的回答,对不起,如果我不清楚,但我希望只有一行结果(为此创建一个脚本似乎太重了,只是想要一些快速的东西)。我一直在考虑更多,到目前为止我想出了这个:
perl -n -e 'chomp($_); print " | grep $_  "' pattern | xargs echo "cat input"

哪个打印
cat input | grep a | grep b | grep c

这个字符串是我想要执行的,我现在只需要以某种方式执行它。我尝试了一个额外的管道来评估
perl -n -e 'chomp($_); print " | grep $_  "' pattern | xargs echo "cat input" | eval

虽然这给出了信息:
xargs: echo: terminated by signal 13

我不确定这意味着什么?

最佳答案

使用 perl 的一种方式:
input的内容:

acb
bc
ca
bac
pattern的内容:
a
b
c
script.pl的内容:
use warnings;
use strict;

## Check arguments.
die qq[Usage: perl $0 <input-file> <pattern-file>\n] unless @ARGV == 2;

## Open files.
open my $pattern_fh, qq[<], pop @ARGV or die qq[ERROR: Cannot open pattern file: $!\n];
open my $input_fh, qq[<], pop @ARGV or die qq[ERROR: Cannot open input file: $!\n];

## Variable to save the regular expression.
my $str;

## Read patterns to match, and create a regex, with each string in a positive
## look-ahead.
while ( <$pattern_fh> ) { 
    chomp;
    $str .= qq[(?=.*$_)];
}

my $regex = qr/$str/;

## Read each line of data and test if the regex matches.
while ( <$input_fh> ) { 
    chomp;
    printf qq[%s\n], $_ if m/$regex/o;
}

像这样运行它:
perl script.pl input pattern

具有以下输出:
acb
bac

关于perl - Grep 匹配模式文件的所有行(perl -e 也可以),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9933680/

相关文章:

perl - VIM 9 Perl 文件的字边界更改

regex - Perl 中的 qr/和 m/有什么区别?

linux - 调用bash脚本在if语句和变量赋值上生成错误

java - 为什么我的 IDE 可以找到 JAR,但我的命令行却找不到?

Perl - 数组哈希 : Key look-up by Value

perl - 如何在 Perl 中将输入文件转换为 UTF-8 编码?

perl - 如何在 Perl 中不活跃

linux - grep 一个左括号

svn - 使用 SVN 查看先前代码的命令

Linux/Shell 切片一个大的文本文件