【问题标题】:How can I calculate a sum of specific csv column by using input on console using Bash [duplicate]如何使用 Bash 在控制台上使用输入来计算特定 csv 列的总和 [重复]
【发布时间】:2020-12-15 09:24:00
【问题描述】:

基本上例如,如果您有一个标题为“Totalreported”的 csv 文件。如果我在命令行中输入“Totalreported”,它应该输出该特定列的所有值的总和。如果例如我有不同的csv,应该是相同的过程。如果我拼错了列名或列名不存在,它不会输出任何内容。 我怎样才能做到这一点?所以脚本中没有硬编码的列名。

这是我尝试过的,但这里是硬编码的值,但我希望它不是硬编码的,这样我就可以使用任何 csv 文件。在这里,您可以看到硬编码的列名称“Deceased”、“Hospital”和“TotalReported”,但我希望我的代码能够根据输入从任何 csv 文件中获取任何列我该如何实现?

#!/bin/bash

updatedata() {

      
            if [ $pos -eq 0 ]
            then
                if [ "$1" = "Deceased" ]
                then
                    v0=$(awk -F";" '{x+=$7}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv )
                
                elif [ "$1" = "Hospital" ]
                then
                    v0=$(awk -F";" '{x+=$6}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv)
                elif [ "$1" = "TotalReported" ]
                then
                    v0=$(awk -F";" '{x+=$5}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv)
                fi
            elif [ $pos -eq 1 ]
            then
                if [ "$1" = "Deceased" ]
                then
                    v1=$(awk -F";" '{x+=$7}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv)
                elif [ "$1" = "Hospital" ]
                then
                    v1=$(awk -F";" '{x+=$6}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv)
                elif [ "$1" = "TotalReported" ]
                then
                    v1=$(awk -F";" '{x+=$5}END{print x}' ./COVID-19_aantallen_gemeente_cumulatief.csv)
                fi
            
            
}

【问题讨论】:

  • 看看awk,它允许您处理文本文件(man awk)。将字符串分隔符设置为逗号,然后就可以过滤掉特定的列并对元素进行求和。
  • awk tutorial 将为您提供awk 工作原理的良好基础。您需要关注for 循环,使用-v var="value" 传递变量、数学运算、sum+=$8(例如)和逻辑比较if ($7 == var) { data_pos=7 } 也将很好地了解BEGIN{}END{} 块工作。祝你好运。
  • StackOverflow 是一个面向程序员的网站。您应该在提问时展示您尝试过的内容。请参阅stackoverflow.com/help/how-to-ask 了解更多信息。
  • 请在您的问题中添加示例输入(无描述、无图像、无链接)以及该示例输入所需的输出(无评论)。

标签: linux bash csv calculated-columns


【解决方案1】:

一个简单的 awk 方法:

$ cat input
foo;bar;baz
1;2;3
4;5;6
7;8;9
$ ./sum.sh foo < input
12
$ ./sum.sh qux < input
$ ./sum.sh baz < input
18
$ cat sum.sh 
#!/bin/sh

: ${FS=;}
col=${1:?}
awk 'NR==1 { for(i = 0; i <= NF; i++) if( $i == col ) c = i; next; }
        c { sum += $c }
        END{ if(c) print sum }
' col="$col" FS="$FS"

【讨论】:

  • 我尝试实现 ./csvtest.sh Deceased 但它没有做任何事情
  • 我使用,作为分隔符。查看您的代码,我发现您想使用;。这需要一些额外的引用。我将编辑使用;
  • 您看到的错误表明第 4 行或第 8 行存在错误复制
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多