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

如何使用Shell Scripting读取.csv文件并执行指定算术运算

CSV多文件对应列算术计算Shell脚本实现

直接使用awk即可实现需求,无需安装额外依赖,适配大部分Linux/Unix默认环境,完整方案如下:

完整脚本

#!/bin/bash

# 可直接执行默认读取当前目录下的sample1.csv、sample2.csv,也可手动传入两个文件路径作为参数
file1="${1:-sample1.csv}"
file2="${2:-sample2.csv}"

awk -F ',' '
# 处理第一个CSV文件,按行存储对应数值
FILENAME == ARGV[1] {
    if ($1 == "Assets") {
        for (i=2;i<=NF;i++) assets[i-1] = $i
    } else if ($1 == "Loans") {
        for (i=2;i<=NF;i++) loans[i-1] = $i
    } else if ($1 == "reported_activity") {
        for (i=2;i<=NF;i++) report[i-1] = $i
    }
    next
}
# 处理第二个CSV文件,按行存储对应数值
FILENAME == ARGV[2] {
    if ($1 == "credit") {
        for (i=2;i<=NF;i++) credit[i-1] = $i
    } else if ($1 == "debit") {
        for (i=2;i<=NF;i++) debit[i-1] = $i
    } else if ($1 == "affilate") {
        for (i=2;i<=NF;i++) affilate[i-1] = $i
    }
    next
}
# 所有文件读取完成后按列计算
END {
    col_total = length(assets)
    print "列序号,计算结果"
    for (col=1;col<=col_total;col++) {
        result = assets[col] + (loans[col] + affilate[col] * -1) + report[col] + (credit[col] - debit[col])
        printf "%d,%d\n", col, result
    }
}
' "$file1" "$file2"

使用方法

  • 将上述内容保存为calc.sh,添加执行权限:chmod +x calc.sh
  • 直接执行:./calc.sh,也可指定文件路径执行:./calc.sh /自定义路径/sample1.csv /自定义路径/sample2.csv

输出结果示例

列序号,计算结果
1,-1
2,15
3,17

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 22:45:03