1

第一个文件内容:

fruit bags    
nice things  
string guitar

第二个文件内容

bagsfruit  
nicefruit  
guitarstring  
simplethings  
stringguitar

我将如何编写 awk 程序以逐行搜索第二个文件中的第一个文件内容,并仅打印第二个文件中包含第一个文件中的任意顺序的两个单词的行。

所以脚本的结果应该是:

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

但不是这些:

nicefruit  
simplethings

谢谢!

4

1 回答 1

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)为索引的数组。然后它检查field1来自 second_file 的哪些在数组中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].

于 2013-05-30T00:03:35.933 回答