File which named as Input.txt
has following data as name, class, schoolName, marks1 and marks2 with #
separator:
Deepu#First#Meridian#95#90 Neethu#Second#Meridian#80#75 Sethu#First#DAV#75#70 Theekshana#Second#DAV#80#79 Teju#First#Sangamithra#88#63 Theekshita#Second#Sangamithra#91#90
Using above file print all the details along with average using |
separator as output.
My answer:
awk 'OFS="|" { avg=0; for(i=4;i<=NF;i++){avg=($4+$5)/2;} print $1,$2,$3,$4,$5,avg}' Input.txt
I tried one more command as:
awk 'OFS="|" {sum=0; for(i=4;i<=NF;i++) sum+=$i; print $1,$2,$3,$4,$5,sum/(NF-2)}' Input.txt
Output looks like this:
Please help me out to get the desired output.
Advertisement
Answer
You have to set FS in the BEGIN, the below works for me
awk 'BEGIN {FS="#"} {avg=0; for(i=0;i<NR;i++) avg=($4 + $5)/2.0;}{OFS="|"}{print $1,$2,$3,$4,$5,avg}' $ awk 'BEGIN {FS="#"} {avg=0; for(i=0;i<NR;i++) avg=($4 + $5)/2.0;}{OFS="|"}{print $1,$2,$3,$4,$5,avg}' mehdi.txt Deepu|First|Meridian|95|90|92.5 Neethu|Second|Meridian|80|75|77.5 Sethu|First|DAV|75|70|72.5 Theekshana|Second|DAV|80|79|79.5 Teju|First|Sangamithra|88|63|75.5 Theekshita|Second|Sangamithra|91|90|90.5 $
Thanks @EdMorton. This can be further shortened as
$ awk ' BEGIN { FS="#";OFS="|"} {$6=($4 + $5)/2.0;$0=$0;print $0 }' mehdi.txt Deepu|First|Meridian|95|90|92.5 Neethu|Second|Meridian|80|75|77.5 Sethu|First|DAV|75|70|72.5 Theekshana|Second|DAV|80|79|79.5 Teju|First|Sangamithra|88|63|75.5 Theekshita|Second|Sangamithra|91|90|90.5 $