如何修改awk命令实现两文件字段匹配后的内容替换?
Let's fix your awk command step by step—there are a few syntax and logic issues in your original script that are causing errors and incorrect output.
What's wrong with your original command?
- Syntax mistake: You didn't add a separator (space or semicolon) after
-F',', soFNR==NRwas being interpreted as part of the field separator argument, which broke the command entirely. - Incorrect lookup reference: Your array
amapsf2.txt's second column to its first, but you tried to accessa[$1]instead ofa[$2]when processingf1.txt—you need to match the second column off1to the keys in your array. - Wrong field order: Your print statement included
$2as the third field, but you should keep the original third column (Count) fromf1.txt(that's$3). - Missing output separator: Awk uses spaces by default for output fields. You need to set the output field separator (
OFS) to a comma to match your input format.
Corrected awk command
Here's the fixed version that will produce exactly the output you want:
awk -F',' -v OFS=',' 'FNR==NR {a[$2]=$1; next} {print $1, ($2 in a ? a[$2] : $2), $3}' f2.txt f1.txt
How this works
Let's break down each part:
-F',': Tells awk to split input lines using commas as the field separator.-v OFS=',': Sets the output field separator to a comma, so our output matches the input's comma-separated format.FNR==NR {a[$2]=$1; next}:- This pattern only runs when processing the first file (
f2.txt).FNRis the line number of the current file, andNRis the total line number across all files—they're equal only for the first file. - We build a lookup array
awhere the key is the second column off2.txt(e.g., "hello world") and the value is the corresponding first column (e.g., "h1"). nextskips the rest of the script for lines fromf2.txt, so we don't print them.
- This pattern only runs when processing the first file (
{print $1, ($2 in a ? a[$2] : $2), $3}:- For lines from
f1.txt, we print the first column (From), then check if the second column (Key) exists in our lookup array. If it does, we use the mapped value; if not, we keep the original key (this is an optional safety net in case there's an unmatched key). Finally, we print the third column (Count).
- For lines from
Test output
Running this command will generate your desired output:
From,Key,Count abc.org,h3,5 abc.com,h1,2 def.com,h2,1 efg.com,h1,1
内容的提问来源于stack exchange,提问作者user2340345
相关产品推荐
相关产品推荐

