AWK技术需求:匹配两文件前两字段并追加对应字段值
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==FNRblock runs only when processing the first input file (here,file2). Instead of counting matches withc[$1$2]++, we store the third field value in an arraymap, using the combination of the first two fields as the key ($1,$2). Using a comma here is safer than concatenating$1$2directly—it avoids accidental key collisions (e.g.,NODE12 INTERFACEvsNODE1 INTERFACE2would 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 fromfile2if the first two fields exist in ourmaparray. 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

