grep for multiple targets
I need to select multiple targets from a file.
I've used grep successfully before when using few targets. For example: egrep 'target1|target2|target3|target4' test.txt > test.out test.txt is a file that contains: target1 A A A A B B B target2 B B B B B B B target3 D F F F F F F target4 F F F F F F F target5 G G G G G G G etc.. How can I do the same thing but instead of using egrep 'target1|target2|target3|target4|etc' use a file that contains a list with all the 1000 targets I'm interested on. Something like: target1 target2 target3 target4 . . . target1000 Thanks, mjtruco |
man grep
Look in the "Matching Control" section for the '-f' switch Does exactly what you're looking for. |
Code:
grep -f pattern_file file |
grep -f didn't work for file with targets
I've tried
grep -f file_targets and it didn't work I get the following error: illegal option --f Usage: grep -hblcnsviw pattern file ... Do you know what is happening? Thanks, mjtruco |
You're probably on an ancient version of Linux, or on a commercial
Unix like solaris. Cheers, Tink |
Code:
awk 'FNR==NR{t[$1];next}($1 in t)' targets file |
I'm not a big user of awk, but won't that only work if the pattern matches the full text - rather than a substring match as seems the requirement ?.
|
Quote:
Code:
FNR==NR{t[$1];next} Code:
($1 in t) |
Thanks - like I said ...
|
Keep it simple:
Code:
while read pattern; do grep $pattern file; done < patterns |
Quote:
1)probably should put a boundary on the grep pattern, eg grep "target1" will also match target10 or target100 ....which will give ambiguous results 2)assuming "patterns" file has 1000 targets as OP has mentioned, so the code will call grep 1000 times on "file". it would be slower than going through the file once( as in the awk example). Its even slower if "file" is a big file. |
ghostdog, you're right as always. Anyway, I suspect the OP does not have GNU awk. I tested your code on a Solaris Sparc 5.8 and it doesn't work, due to a syntax error
Code:
$ awk 'FNR==NR{t[$1];next}($1 in t)' targets file |
use nawk on Solaris
|
Quote:
|
You were right. I was using an old version of Solaris.
I've changed to a new version from GNU Free Software Foundation and the command grep -f worked fine. Thanks for the help mjtruco |
All times are GMT -5. The time now is 11:48 PM. |