awk从另一个文件中的一个文件中搜索多个单词模式

时间:2013-05-29 23:49:45

标签: awk design-patterns

第一个文件内容:

fruit bags    
nice things  
string guitar

第二档案内容

bagsfruit  
nicefruit  
guitarstring  
simplethings  
stringguitar

我如何编写awk程序在第二个文件中逐行搜索第一个文件内容,并且只打印第二个文件中的行,其中包含任意顺序,包含第一个文件中的单词..

所以脚本的结果应该是:

bagsfruit  
guitarstring  <--any order  
stringguitar  <--any order

但不是以下任何一种:

nicefruit  
simplethings

谢谢!

1 个答案:

答案 0 :(得分:1)

这可行:

$ awk 'NR == FNR{a[$2$1];next} ($1 in a)' first_file second_file
bagsfruit  
guitarstring  

代码基于Idiomatic awk的示例。

基本上它循环遍历first_file并创建一个数组a[]fi[eld2 field1](即$2$1)作为索引。然后它检查来自second_file的field1在数组a[]中并打印出来。


更新

$ awk 'NR == FNR{a[$2$1];a[$1$2];next} ($1 in a)' first_file seconf_file
bagsfruit  
guitarstring  
stringguitar

让我们每次创建两个数组索引,[$1$2][$2$1]