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

如何用awk实现匹配追加数据并添加指定表头?

问题解决:用Awk合并文件并添加表头

需求说明

我写了一段Awk脚本,想把file1的$1存入数组a,匹配file2的$1后,将file2的$2追加到file1对应行后面。同时要给新增列加表头“Number”,但不知道怎么实现。

file1(逗号分隔)

[...],,
...,
[...],,
...,
[Data],,
ID,_A,_B
aaa00-00,...,0
aaa00-11,...,1
aaa00-22,...,2

file2(空格分隔)

aaa00-00 0.1257
aaa00-11 0.1263
aaa00-22 0.1239

期望输出(逗号分隔)

[...],,
...,
[...],,
...,
[Data],,
ID,_A,_B,Number
aaa00-00,...,0,0.1257
aaa00-11,...,1,0.1263
aaa00-22,...,2,0.1239

当前Awk脚本

awk '
BEGIN   { FS=OFS="," }       # define FS an OFS as comma
/^Data/    { next }          # only operate in the Data section or move on
FNR==NR { a[$1]=$1; next }   # condition which will be TRUE when file2 is being read and creating array a with index of $1 and value of $1
    { $4= ($2 in a) }        # check if 1st field matches and printing value in $4 if it does
1
' file1 file2

修正后的Awk脚本

awk '
BEGIN {
    FS=OFS=","
}
# 先处理file2,存储ID对应的值
FNR==NR {
    a[$1]=$2
    next
}
# 保留[Data]行直接输出
/^\[Data\]/ {
    print
    next
}
# 给表头行追加"Number"
$1=="ID" {
    print $0 OFS "Number"
    next
}
# 数据行匹配ID并追加对应值
{
    print $0 ($1 in a ? OFS a[$1] : "")
}
' file2 file1

关键修正点

  1. 调整文件处理顺序:先读file2,把ID作为数组索引,对应数值存入数组a,后续处理file1时直接取值
  2. 修复数组存储逻辑:原脚本存的是ID本身,现在改为存file2的对应数值
  3. 保留[Data]行:原脚本会跳过该行,现在改为直接输出
  4. 添加表头:识别表头行ID,_A,_B,直接追加Number
  5. 修正匹配逻辑:原脚本判断$2是否在数组,实际应该判断file1的$1是否匹配file2的$1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:35:27