Hi Friends,
Can any one help me with count average of student marks in this file (i can not change structure of the input file):
input file:
1:John Smith:2 3 4 5
2:Mark Anderson:3 2
3:Susan Waterman:2 4 2
(numbers of marks are different)
output:
Name:John Smith
ID#: 1
Avg. mark: 3.5
Name:Mark Anderson
ID#: 2
Avg. mark: 2.5
Name:Mark Anderson
ID#: 2
Avg. mark: 2.6667
Name:Susan Waterman
ID#: 3
Avg. mark: 2.5
Hope this helps set you in the right direction:
#!/usr/bin/env perl
use strict;
# define the file
my $file = "in-file.txt";
# open the file and dump it's contents into an array
open(FILE, "<$file") or die "Unable to open $file: $!\n";
my @FILE_IN = <FILE>;
close(FILE);
# define a couple of variables we'll need
my $total;
my $average;
# loop through the file and parse out the name, id, and the average
foreach(@FILE_IN) {
chomp;
if ($_ =~ /^([0-9]+).(\w+\s\w+).(.*)/) {
print "Name: $2\n";
print "ID#: $1\n";
my @MARKS = split('\s', $3);
my $num_of_marks = $#MARKS + 1;
foreach\(@MARKS\) \{
$total \+= $_;
\}
my $average = $total / $num\_of_marks;
\# adjust %.1f to the desired number of decimal places
printf "Avg. mark: %.1f\\n\\n", $average;
\# reset the total and average variables
\# otherwise they'll be carried over
\# to the next run through the loop
$total = 0;
$average = 0;
\} else \{
print "There was a problem!\\n";
exit\(1\);
\}
}
exit(0);
With Awk:
awk -F: '{ n = split($NF, _, OFS)
for (i=1; i<=n; i++) s += _
printf "Name: %s\nID#: %d\nAvg. mark: %.1f\n\n",\
$2, $1, s/n; s = 0 }' input
What means?
%s
What I should change if input file will look little bit different:
I add 2 columns, so marks are now at 5 th column
1:John Smith:1:2:2 3 4 5
2:Mark Anderson::2:3:3 2
3:Susan Waterman::7:1:2 4 2
Yes , I try it.
But i do not understand what means %s?
Could anyone help me with that 2 additional columns at AWK?