Grep to match all the patterns from a file

你。 提交于 2019-12-11 13:08:59

问题


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).

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:

1
2
12

pattern.f:

1
2

And I run this command:

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

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).


回答1:


It might be better to use awk:

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

This reads the patterns into the array a[].

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.



来源:https://stackoverflow.com/questions/28896544/grep-to-match-all-the-patterns-from-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!