user2555158
user2555158

Reputation: 1

How can I use multiple field separators or multiple awk to process columns

I have a tab separated file which looks like the following

John  1,0   3,2   5,6
Mike  3,2    4,5   0,0
James 3,0    5,3   4,5

I would like to add all the first elements of 3 fields and add second elements of 3 fields output the following

John 9,8
Mike 9,7
James 12,8 

Is there is a solution in awk where I can use multiple field separators?

Upvotes: 0

Views: 136

Answers (3)

Ed Morton
Ed Morton

Reputation: 203493

$ awk -F'[\t,]' '{delete s; for (i=2;i<=NF;i++) s[i%2]+=$i; print $1 "\t" s[0] "," s[1]}' file
John    9,8
Mike    7,7
James   12,8

Upvotes: 1

anubhava
anubhava

Reputation: 785128

You can use multiple delimiters in awk:

awk -F '[\t,]+' -v OFS='\t' '{print $1, ($2+$4+$6) "," ($3+$5+$7)}' file

John    9,8
Mike    7,7
James   12,8

Upvotes: 5

redneb
redneb

Reputation: 23850

I don't know about awk but here's a (boring) solution with bash:

while read -r name f1 f2 f3; do
    s1=$((${f1%,*}+${f2%,*}+${f3%,*}))
    s2=$((${f1#*,}+${f2#*,}+${f3#*,}))
    echo "$name $s1,$s2"
done < input.txt

Upvotes: 1

Related Questions