Reputation: 877
My input file is as below
file name: marksheet
No Name Sub1 Sub2 Sub3
1 Atul 89 56 78
2 Jay 56 88 75
3 Mariya 85 75 56
4 Nita 90 88 95
Now i want to perform total and percentage. So i performed below command
awk 'total=$3+$4+$5, per=total/3 {print total "\t" per}' marksheet
it gives output of total and column. as
223 74.3333
219 73
216 72
273 91
So now i want to add above column( output) in file marksheet. So if it is possible then how to perform the command using awk.
Upvotes: 1
Views: 550
Reputation: 37404
As I had never used the -i
switch and inplace editing (in Gnu awk since v. 4.1.0 (gawk -V
), according to awk save modifications in place) I decided to take it for a spin. I took OP's example data and code and went with it:
$ awk -i inplace -v INPLACE_SUFFIX=.bak 'NR==1 && $6="total", $7="per"; NR>1 && $6=$3+$4+$5, $7=$6/3' OFS='\t' file
$ cat file
No Name Sub1 Sub2 Sub3 total per
1 Atul 89 56 78 223 74.3333
2 Jay 56 88 75 219 73
3 Mariya 85 75 56 216 72
4 Nita 90 88 95 273 91
And the backup:
$ cat file.bak
No Name Sub1 Sub2 Sub3
1 Atul 89 56 78
2 Jay 56 88 75
3 Mariya 85 75 56
4 Nita 90 88 95
Spacing difference comes from real tabs in output vs. cut'n pasting the question for input.
Upvotes: 0
Reputation: 18381
Begin statement is to define header of the file. you have already calculated sum and average. Printed $0
means whole line and then total
and then per
variables which contains value of sum and average value. OFS
here make awk
aware of the output fields to be separated using tab.
awk -v OFS="\t" 'BEGIN{print "No Name Sub1 Sub2 Sub3 total percent"} NR>1{total=$3+$4+$5; per=total/3 ;print $0 ,total,per }' marksheet
No Name Sub1 Sub2 Sub3 total percent
1 Atul 89 56 78 223 74.3333
2 Jay 56 88 75 219 73
3 Mariya 85 75 56 216 72
4 Nita 90 88 95 273 91
To actually modify your base file:
awk -v OFS="\t" 'BEGIN{print "No Name Sub1 Sub2 Sub3 total percent"} NR>1{total=$3+$4+$5; per=total/3 ;print $0 ,total,per }' marksheet >marksheet.tmp && mv marksheet.tmp marksheet
Upvotes: 2