davoid
davoid

Reputation: 327

Sum values of specific columns using awk

So I have a file which looks like this:

1 4 6 
2 5
3

I want to sum only specific columns, let's say the first and third. And the output should look like this:

7
2
3

I store numbers of columns (arguments) in a variable: x=${@:2} (because I omit first passed argument which is a $filename)

How to calclute this using awk in a bash script ? I was thinking about sth like this

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

done

But it does not work properly.

Upvotes: 2

Views: 1875

Answers (2)

James Brown
James Brown

Reputation: 37464

How about something like this:

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

Explained:

$ 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

EDIT: changed comma-separation to space-separation.

Upvotes: 5

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{print $1 + $3}' file
7
2
3

Upvotes: 1

Related Questions