来自 2 列的 awk 字符串匹配

Ash*_*Ash 2 shell grep awk text-processing

我有一个文件(文件 1),其内容如下:

2  test1
3  test2 
2  test3 
1  test1 
4  test2
Run Code Online (Sandbox Code Playgroud)

还有一个主文件(file2):

2    test1
3  test1
4         test1
2  test2
3 test2
4   test2
5 test2 
...
Run Code Online (Sandbox Code Playgroud)

当文件 1 中的第 1 列和第 2 列匹配时,我想打印文件 2 中的所有行。我想保留文件 2 的随机格式。什么是最好的方法来做到这一点?

Arc*_*mar 7

尝试

awk 'NR==FNR { a[$1 $2]=1 ; } NR>FNR { if ( $1 $2 in a ) print ;}'
Run Code Online (Sandbox Code Playgroud)

在哪里

  • NR==FNR 记录数 == 文件记录数(我们在第一个文件中)
  • { a[$1 $2]=1 ; } 存储密钥(没有空格的连接)
  • NR>FNR (我们在第二个文件中)
  • if ( $1 $2 in a ) 如果索引在当前...
  • print 打印该行。

给你样品

2    test1
3 test2
4   test2
Run Code Online (Sandbox Code Playgroud)

  • 可以简化为 `awk 'NR==FNR { a[$1 $2] ; next} ( $1 $2 in a )'` (3认同)

JJo*_*oao 5

awk 'n[$1][$2]++'   file1 file2
Run Code Online (Sandbox Code Playgroud)

假设两个文件中都没有重复项。

  • 次要问题:如果`file1` 中有重复的行,这会中断。一个可能的修复:`awk 'n[$1][$2]++ && NR!=FNR' file1 file2`。 (3认同)