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

发布于 2024-08-31 19:09:29 字数 633 浏览 5 评论 0原文

我有一个包含 2 列的文件,如下所示......

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

等等......

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

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

I have a file that has 2 columns as given below....

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

and so on......

I want to write a script that adds the values from 2nd column if their corresponding first column matches

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 ...

i wrote my script like this , but i'm not getting the correct result

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北音执念 2024-09-07 19:09:29
awk '{array[$1]+=$2} END { for (i in array) {print "Sum for time stamp",i,"=", array[i]}}' data.txt
awk '{array[$1]+=$2} END { for (i in array) {print "Sum for time stamp",i,"=", array[i]}}' data.txt
杀お生予夺 2024-09-07 19:09:29

纯 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

Pure 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

The output:

101 48
102 47
103 45
108 21
109 103
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文