grep匹配模式文件的所有行(perl -e ok)
发布时间:2020-12-16 06:22:46 所属栏目:大数据 来源:网络整理
导读:我正在寻找一种简单/优雅的方式来grep文件,使每个返回的行必须匹配模式文件的每一行. 带输入文件 acbbccabac 和模式文件 abc 该命令应该返回 acbbac 我尝试使用grep -f执行此操作,但如果它匹配文件中的单个模式(而不是全部),则会返回.我还尝试了对perl -ne的
我正在寻找一种简单/优雅的方式来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[%sn],$_ if m/$regex/o; } 运行它像: perl script.pl input pattern 输出如下: acb bac (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |