我正在寻找一种简单/优雅的方式来grep文件,使每个返回的行必须匹配模式文件的每一行.
带输入文件
acb bc ca bac
和模式文件
a b c
该命令应该返回
acb bac
我尝试使用grep -f执行此操作,但如果它匹配文件中的单个模式(而不是全部),则会返回.我还尝试了对perl -ne的递归调用(模式文件的foreach行,在搜索文件上调用perl -ne并尝试grep到位)但我无法让语法解析器接受对perl的调用来自perl,所以不确定这是否可行.
我认为这可能是一种更优雅的方式,所以我想我会检查一下.谢谢!
=== UPDATE ===
感谢您的答案到目前为止,对不起,如果我不清楚,但我希望只有一个单行结果(创建一个脚本,这似乎太沉重,只是想快点).我一直在考虑它,到目前为止我想出了这个:
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的一种方法:
输入内容:
acb bc ca bac
模式内容:
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,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