$ cat file
a:12:56:12
b:23:12:23
d:32:24:12
c:90:12:24
required output:
a:12:56:12
b:23:12:23
d:32:24:12
c:90:12:24
t:157:104:71
t line is the total line, which will be the last line in the output.
Please help.
I tried this:
$ awk 'BEGIN {FS=OFS=":"}{sum+=$2} {sum1+=$3} {sum2+=$4} END {print "t",sum,sum1,sum2}' file
t:157:104:71
How can perform the same using a for loop in awk, please help.
{ for (i=2; i<=NF; ++i) sum += $i; j=NF }
END { printf "%s", t; for (i=2; i <= j; ++i) printf "%s%s", OFS, sum; printf "\n"; }
There's probably a more elegant way ...
Print the lines first.
awk 'BEGIN {FS=OFS=":"}{print; sum+=$2; sum1+=$3; sum2+=$4} END {print "t",sum,sum1,sum2}' file
Another one in awk::
awk -F":" '{ print; } END { while((getline < "filename")>0) { var1+=$2;var2+=$3;var3+=$4; } print "t:"var1":"var2":"var3; }' filename
Do you really want to parse the file a second time?