0

Looping over the whole column sum using can be done in the below txt file this:

101     10
101     10
101     10.10
101     13
101     10
101     10
102     10.140
102     10
102     10
102     0.90
102     10
103     10
104     10
111     11
111     11
111     5.485e+12
111     11


 awk '{sum+=$2;} END{print sum;}' file1.txt > sum_a.txt

Now I would like to do something different. For example, I would like to sum the second columns upto when the first column numbers are same and start over again. Can it be done using seen[$1]?

awk '{ seen[$1] += $2 } END { for (i in seen) print i, seen[i] }' file1.txt

where $1 being treated as the index value.

I couldn't make it run using seen[$1]. Or Any other nice way to do the looping?

The result would be like this:

101     63.10
101     63.10
101     63.10
101     63.10
101     63.10
101     63.10
102     40. 90

and so on... up to the whole column.

1
  • 2
    The array name seen[] is idiomatically used to test whether or not a given index has been seen previously so you do perform actions the first time a value is seen vs subsequent times. It is invariable used in the context of if ( seen[$1]++ ) print "first time"; else print "subsequent time". It is NOT used as the name of an array to hold other numerical values - those arrays would be named sum[] or cnt[] or tot[] or ave[], etc.
    – Ed Morton
    Apr 10, 2020 at 4:51

2 Answers 2

2
$ awk 'NR==FNR{sum[$1]+=$2; next} {print $1, sum[$1]}' file file
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
102 41.04
102 41.04
102 41.04
102 41.04
102 41.04
103 10
104 10
111 5485000000033
111 5485000000033
111 5485000000033
111 5485000000033
2
  • Just out of curiosity. Doesn't the printf function allow here too to print out with power form? like this : awk 'NR==FNR{sum[$1]+=$1; next} {printf "%.5e\n", $1, sum[$1]}' Apr 10, 2020 at 6:05
  • Why not just try it and see?
    – Ed Morton
    Apr 10, 2020 at 12:41
0

If just want to use only one input file using awk:

 $ awk -v c=1 '{ a[$1]+=$2;b[c]=$1;c+=1} END { for( i=1;i<=NR;i++ ){key=b[i]; print key" "a[key]} }' file1.txt  
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
101 63.1
102 41.04
102 41.04
102 41.04
102 41.04
102 41.04
103 10
104 10
111 5485000000033
111 5485000000033
111 5485000000033
111 5485000000033

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .