78.0k views
1 vote
(6 pts) Write a bash shell script called 08-numMajors that will do the following: i. Read data from a class enrollment file that will be specified on the command line. ii. If the file does not exist, is a directory, or there are more or less than one parameters provided, display an appropriate error/usage message and exit gracefully. iii. Display the number of a specified major who are taking a given class.

User Vlood
by
4.5k points

1 Answer

7 votes

Answer:

Check the explanation

Step-by-step explanation:

Script:

#!/usr/bin/ksh

#using awk to manipulated the input file

if [ $# != 1 ]

then

echo "Usage: 08-numMajors.sh <file-name>"

exit 1

fi

if [ -f $1 ]

then

awk '

BEGIN {

FS=","

i=0

flag=0

major[0]=""

output[0]=0

total=0

}

{

if ($3)

{

for (j=0; j<i; j++)

{

# printf("1-%s-%s\\", major[j], $3);

if(major[j] == $3)

{

flag=1

output[j] = output[j] + 1;

total++

}

}

if (flag == 0)

{

major[i]=$3

output[i] = output[i] + 1;

i++;

total++

}

else

{

flag=0

}

}

}

END {

for (j=0; j<i; j++)

{

if(output[j] > 1)

printf("There are %d `%s` majors\\", output[j], major[j]);

else

printf("There is %d `%s` major\\", output[j], major[j]);

}

printf("There are a total of %d students in this class\\", total);

}

' < $1

else

echo "Error: file $1 does not exist"

fi

Output:

USER 1> sh 08-numMajors.sh sample.txt

There are 4 ` Computer Information Systems` majors

There is 1 ` Marketing` major

There are 2 ` Computer Science` majors

There are a total of 7 students in this class

USER 1> sh 08-numMajors.sh sample.txtdf

Error: file sample.txtdf does not exist

USER 1> sh 08-numMajors.sh

Usage: 08-numMajors.sh <file-name>

USER 1> sh 08-numMajors.sh file fiel2

Usage: 08-numMajors.sh <file-name>

User Jan Schmitz
by
5.1k points