简体   繁体   中英

Grep to match patterns of an external file

I am looking for something like unix grep, that can get the paterns from an external file.

I have a list of patterns on an file patterns.txt like this (but with much more entries):

234523.34
623253.45
3466.55

There is another file called to_search_on.txt and I need to keep only the lines that match patterns.txt. This is to_search_on.txt file (but with more entries to):

kaosar,23443.44,0
ratro,2423545,0
pencod,3466.55,1

How can I do this? thanks

You can use -f option to read patterns from file

$ grep -f patterns.txt to_search_on.txt
pencod,3466.55,1

For more info man grep would give you as

  -f FILE, --file=FILE
              Obtain patterns from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.

You can use awk

awk -F, 'FNR==NR {a[$0]++;next} ($2 in a)' patterns.txt to_search_on.txt
pencod,3466.55,1

This will only give hit if pattern is found in second field (divided by , )
It store the patterns.txt file in array a , then test it against to_search_on.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM