问题
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