You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWK技术需求:匹配两文件前两字段并追加对应字段值

AWK: Match First Two Fields Between Two Files and Append Corresponding Third Field

Let's tweak your existing AWK code to not just identify matching lines, but actually append the third field from file2 to the corresponding lines in file1. Here's the solution:

Working Script

awk 'NR==FNR { map[$1,$2] = $3; next } { print $0, ($1,$2) in map ? map[$1,$2] : "" }' file2 file1

How It Works

Let's break down the changes from your original code:

  • Reading file2 first: The NR==FNR block runs only when processing the first input file (here, file2). Instead of counting matches with c[$1$2]++, we store the third field value in an array map, using the combination of the first two fields as the key ($1,$2). Using a comma here is safer than concatenating $1$2 directly—it avoids accidental key collisions (e.g., NODE12 INTERFACE vs NODE1 INTERFACE2 would create the same concatenated key, but the comma-separated pair won't).
  • Processing file1: For each line in file1, we print the entire original line ($0), followed by the third field from file2 if the first two fields exist in our map array. If there's no match, we append an empty string (you can adjust this to skip unmatched lines entirely if needed—see the note below).

Example Output

Using your sample files:

File1 content:

NODE1 INTERFACE1 515
NODE1 INTERFACE2 511
NODE2 INTERFACE1 261
NODE2 INTERFACE2 51
NODE3 INTERFACE1 725
NODE3 INTERFACE2 611

File2 content:

NODE1 INTERFACE1 616
NODE1 INTERFACE2 15
NODE2 INTERFACE1 61
NODE2 INTERFACE2 788
NODE3 INTERFACE1 999
NODE3 INTERFACE2 888

Running the script will produce:

NODE1 INTERFACE1 515 616
NODE1 INTERFACE2 511 15
NODE2 INTERFACE1 261 61
NODE2 INTERFACE2 51 788
NODE3 INTERFACE1 725 999
NODE3 INTERFACE2 611 888

Optional Adjustment

If you don't want to output lines from file1 that have no matching entry in file2, modify the script to:

awk 'NR==FNR { map[$1,$2] = $3; next } ($1,$2) in map { print $0, map[$1,$2] }' file2 file1

This will only print lines from file1 where a match exists in file2.

内容的提问来源于stack exchange,提问作者user3746195

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:10:08