代码之家  ›  专栏  ›  技术社区  ›  Sharat Chandra

搜索字符串,如果匹配则添加

  •  2
  • Sharat Chandra  · 技术社区  · 16 年前

    我有一个文件有两列,如下所示…

    101   6
    102   23
    103   45
    109   36
    101   42
    108   21
    102   24
    109   67
    

    等等……

    我想编写一个脚本,如果第2列的值对应的第一列匹配,则添加第2列的值

    for example add all 2nd column values if it's 1st column is 101
    add all 2nd column values if it's 1st colummn is 102
    add all 2nd column values if it's 1st colummn is 103 and so on ...
    

    我写了这样的脚本,但没有得到正确的结果

    awk '{print $1}' data.txt > col1.txt
    while read line
    do
        awk ' if [$1 == $line] sum+=$2; END {print "Sum for time stamp", $line"=", sum}; sum=0' data.txt
        done < col1.txt
    
    2 回复  |  直到 16 年前
        1
  •  3
  •   Dennis Williamson    16 年前
    awk '{array[$1]+=$2} END { for (i in array) {print "Sum for time stamp",i,"=", array[i]}}' data.txt
    
        2
  •  3
  •   Fritz G. Mehner    16 年前

    纯bash:

    declare -a sum
    while read -a line ; do
      (( sum[${line[0]}] += line[1] ))
    done < "$infile"
    
    for index in ${!sum[@]}; do
      echo -e "$index ${sum[$index]}"
    done
    

    输出:

    101 48
    102 47
    103 45
    108 21
    109 103