Reputation: 955
Input File
name;x1;x2
jon,doe;10;20
sam,smith;11;21
This is what i have tried so far
awk 'BEGIN {print "name\tx1\tx2\tAvg"} {s+=$2} {k+=$3} {print $1,"\t",$2,"\t",$3,"\t",($2+$3)/2} END {print s/2,k/2}' input.txt
I am trying to find the average of rows and columns from an input file but at the end i am getting one zero that i don't need and i believe that is due to white space. Can someone help me how to handle white space here ?
The expected output should be :
name;x1;x2 Average
jon,doe;10;20 15
sam,smith;11;21 16
Average 10.5 20.5
Upvotes: 0
Views: 68
Reputation: 113814
The default input field separator for awk is whitespace. That doesn't work for your file where the field separator is a semicolon. To fix that, use the -F\;
option. With a few other minor changes, try:
$ awk -F';' '{sub(/^ +/,"");} NR==1 {print $0, "Avg";next} {s+=$2} {k+=$3} {print $0,($2+$3)/2} END {print "Ave",s/(NR-1),k/(NR-1)}' OFS='\t' input.txt
name;x1;x2 Avg
jon,doe;10;20 15
sam,smith;11;21 16
Ave 10.5 20.5
The sample output in the question and as above has a mix of semicolons and whitespace for field separators. If you want to consistently use semicolons:
$ awk -F';' '{sub(/^ +/,"");} NR==1 {print $0, "Avg";next} {s+=$2} {k+=$3} {print $0,($2+$3)/2} END {print "Ave",s/(NR-1),k/(NR-1)}' OFS=';' input.txt
name;x1;x2;Avg
jon,doe;10;20;15
sam,smith;11;21;16
Ave;10.5;20.5
Upvotes: 2