【问题标题】:Sum values of specific columns using awk使用 awk 对特定列的值求和
【发布时间】:2020-08-21 14:30:56
【问题描述】:

所以我有一个看起来像这样的文件:

1 4 6 
2 5
3

我只想对特定列求和,比如说第一列和第三列。 输出应该是这样的:

7
2
3

我将列数(参数)存储在一个变量中: x=${@:2}(因为我省略了第一个传递的参数,即 $filename

如何在 bash 脚本中使用 awk 进行计算? 我在想这样的事情

for i in ${@:2}
do
    awk  -v c=$i '{sum+=$c;print sum}' $fname

done

但它不能正常工作。

【问题讨论】:

    标签: bash awk


    【解决方案1】:

    这样的事情怎么样:

    $ awk -v c="1 3" 'BEGIN{split(c,a)}{c=0;for(i in a) c+=$a[i]; print c}' file
    7
    2
    3
    

    解释:

    $ awk -v c="1 3" '  # the desired column list space-separated
    BEGIN {
        split(c,a)      # if not space-separated, change it here
    }
    {
        c=0;            # reusing col var as count var. recycle or die!
        for(i in a)     # after split desired cols are in a arr, ie. a[1]=1, a[2]=3
            c+=$a[i];   # sum em up
        print c         # print it
    }' file
    

    编辑:将逗号分隔更改为空格分隔。

    【讨论】:

    • 但是如果我想要变量 x=${@:2} 中的更多参数怎么办。例如对于较大的文件,这个变量 x 是 1 2 3 4 5 6 ?
    • awk -v c=$x ... if x="1 2 3 4 5 6".
    • 谢谢我在 for 循环中使用 awk 但你的解决方案更好:)
    • 我知道。这个地方教会我少使用 Bash,将更多功能转移到 Awk(和其他工具)。
    【解决方案2】:
    awk '{print $1 + $3}' file
    7
    2
    3
    

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 2014-10-29
      • 2015-04-11
      • 2015-10-08
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-12
      相关资源
      最近更新 更多