Grep匹配文件中的所有模式 [英] Grep to match all the patterns from a file

查看:65
本文介绍了Grep匹配文件中的所有模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件中有一组模式字符串,我想让 grep 查找与所有模式(逻辑与)匹配的行.

I have a set of pattern strings in a file and I want to have grep find lines that match all of the patterns (logical AND).

在我的示例中,我只想查找包含 1 2 (即 12 )的最后一行,但是实际上匹配中发生的是逻辑或",因此返回所有行:

In my example I want to only find the last line containing both 1 AND 2 (that is, 12), but what actually happens in the match is a logical OR, so all lines are returned:

test_file.txt:

test_file.txt:

1
2
12

pattern.f:

pattern.f:

1
2

然后我运行以下命令:

$ grep -f pattern.f test_file.txt
1
2
12

我可以让 grep 在一行中做我想要的吗?我真的不是必须要编写脚本来读取模式匹配文件并循环一堆垃圾或使用管道( grep 1 test_file.txt | grep 2 ).

Can I make grep do what I want in one line? I don't really want to have to write a script to read the pattern match file and loop a bunch of greps or use pipes (grep 1 test_file.txt | grep 2).

推荐答案

使用 awk 可能会更好:

$ awk 'FNR==NR {a[$1]; next} {for (i in a) if ($1 !~ i) next; print}' patt file
12

这会将模式读入数组 a [] .

然后,当读取 file 时,它将遍历所有模式.如果其中之一与当前行不匹配,它将跳至下一行.如果到达比较的末尾,则意味着该行与所有模式都匹配,然后将其打印出来.

Then, when reading file it loops through all the patterns. If one of them does not match with the current line, it skips to the next line. If it arrives to the end of the comparison, meaning the line matches all the patterns, then it prints it.

这篇关于Grep匹配文件中的所有模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆