You have file named details.txt like following 1798841 | Ragav Sen | Physics | 9
ID: 3682052 • Letter: Y
Question
You have file named details.txt like following 1798841 | Ragav Sen | Physics | 92 1798691 | Sasanka Sethi | Physics |95 1798681 | Ramesh Venkat | Physics | 92 179870 | Suman Sana | Physics | 93 179880 | Suraj Das | Physics | 99 Each line consists of field ID, name, subject and score and fields are pipe delimited. Write awk script in a file dtl.awk which will do the following When the code will be executed, it will display name and score of each student in format 'Name= ,Score=' where , are actual name and score from file. After displaying all the records it should display the average score of all the students. Mention how to execute the code on the given file. Write a perl script with following Declare an array variable and two other variable to store average and no of students Open dtl.txt in input mode and print error if file opening fails Split input line using delimiter pipe (|) and put the values in declared array Print the name and score of the student and keep on computing no of students and average as each line is read Print averageExplanation / Answer
AWK Script :
#! /bin/sh
total=1
awk -F"|" '{print "Name="$2, "Score = "$4;};' $1
awk -F"|" '{ tot += $4; n += 1; } END { print "Average Score : " tot/n; }' $1
Save it and call like :
sh scroe.sh your_file_path
I will write perl script shortly. Let me know if you have anu doubt in awk code.
#!/usr/bin/perl
my $filename = '/home/raghunandangupta/mygit/tally/demo.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
print "<Name>,<Score> ";
my $sum = 0.0;
my $rows = 0;
while (my $row = <$fh>) {
chomp $row;
my @words = split /|/, $row;
$sum +=$words[3];
$rows += 1;
print "$words[1],$words[3] ";
}
print "Average Score : ";
print int($float + $sum/$rows);
print " ";
Save it score.pl and execute using "perl score.pl"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.