简体   繁体   English

Grep匹配外部文件的模式

[英]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. 我正在寻找像unix grep这样的东西,可以从外部文件中获取paterns。

I have a list of patterns on an file patterns.txt like this (but with much more entries): 我有像这样的文件patterns.txt的模式列表(但有更多的条目):

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. 还有一个名为to_search_on.txt的文件,我只需要保留与patterns.txt匹配的行。 This is to_search_on.txt file (but with more entries to): 这是to_search_on.txt文件(但有更多条目):

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 您可以使用-f选项从文件中读取模式

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

For more info man grep would give you as 欲了解更多信息man grep会给你带来的信息

  -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

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 它将patterns.txt文件存储在数组a ,然后针对to_search_on.txt进行测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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