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

如何处理TSV文件列内逗号分隔值,求和新增列并计算百分比?

解决方案

直接用awk处理即可,awk流式处理的特性完全适配超大文件场景,不会出现内存不足的问题,处理逻辑如下:

完整处理脚本

BEGIN {
    # 指定输入输出分隔符为制表符,适配TSV格式
    FS = OFS = "\t"
}
# 处理表头
NR == 1 {
    print $0, "Total_Age", "Total_Weight", "Total_Height", "Percentage"
    next
}
# 处理数据行
{
    # 计算Age列总和
    total_age = 0
    split($3, age_arr, ",")
    for (i in age_arr) total_age += age_arr[i]

    # 计算Weight列总和
    total_weight = 0
    split($4, weight_arr, ",")
    for (i in weight_arr) total_weight += weight_arr[i]

    # 计算Height列总和
    total_height = 0
    split($5, height_arr, ",")
    for (i in height_arr) total_height += height_arr[i]

    # 计算百分比,规避Weight总和为0时报除零错误
    percentage = total_weight == 0 ? 0 : total_height / total_weight

    # 格式化输出,数值精度匹配示例要求
    printf("%s\t%d\t%d\t%.1f\t%.3f\n", $0, total_age, total_weight, total_height, percentage)
}

使用方法

  1. 将上述脚本保存为calc_total.awk
  2. 执行命令处理你的TSV文件:
awk -f calc_total.awk 你的输入文件路径.tsv > 结果输出路径.tsv

处理后的输出完全符合你给出的预期格式,支持GB级以上的大文件处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:24:05