Reputation: 2783
I have a bash program which extracts marks from a file that looks like this:
Jack ex1=5 ex2=3 quiz1=9 quiz2=10 exam=50
I want the code to execute such that when I input into terminal:
./program -ex1 -ex2 -ex3
Jack does not have an ex3 in his data, so an output of 0 will be returned:
Jack 5 3 0
how do I code my program to output 0 for each unrecognized argument?
Upvotes: 0
Views: 43
Reputation: 84561
If I understand what you are trying to do, it isn't that difficult. What you need to do is read each line into a name
and the remainder into marks
. (input is read from stdin
)
Then for each argument given on the command line, check if the first part matches the beginning of any grade in marks
(the left size of the =
sign). If it does, then save the grade
(right side of the =
sign) and set the found
flag to 1
.
After checking all marks against the first argument, if the found
flag is 1
, output the grade
, otherwise output 0
. Repeat for all command line arguments. (and then for all students in file) Let me know if you have questions:
#!/bin/bash
declare -i found=0 # initialize variables
declare -i grade=0
while read -r name marks; do # read each line into name & marks
printf "%s" "$name" # print student name
for i in "$@"; do # for each command line argument
found=0 # reset found (flag) 0
for j in $marks; do # for each set of marks check for match
[ $i = -${j%=*} ] && { found=1; grade=${j#*=}; } # if match save grade
done
[ $found -eq 1 ] && printf " %d" $grade || printf " 0" # print grade or 0
done
printf "\n" # print newline
done
exit 0
Output
$ bash marks_check.sh -ex1 -ex2 -ex3 < dat/marks.txt
Jack 5 3 0
Upvotes: 2