简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM