how to update a file with info from standard input (keyboard) with shell script?
Basically what I have to do is this:
I have a file containing names of students and their partial grades:
(firstname lastname grade)
And what I have to do is update that file with their exam grades and their final grades:
(partial+exam)/2
The exam grades are introduced via the keyboard. So I have to echo a student's name and read his exam grade from the keyboard, and update his line within the file, then move on to the next one, and when I'm all done sort it after the final grade column.
I'm stuck at reading the exam grade from the keyboard. I've tried using some form of awk
and sed
but cant get it to work (cant get the info from the keyboard) and I'm not even sure if thats how it has to be done.
Please help.
ty in advance, bando
edit: (ty for editing, im a bit new to this)
input looks like this:
Tom Green 7
Jenny Patricks 6
Andrew Gibbs 3
Collin Matthews 10
开发者_开发问答it has to run from a script. while running it should put to standard output the first and last name of a student and ask for his grade. once given it edits the file to look like:
Tom Green 7 9 8
and then steps to the next student.
This script does something similar you want:
#!/bin/bash
# $1 input file
# $2 output file (or equal to $1 if ommitted)
if [ -z "$2" ]; then
OUTFILE=$1
else
OUTFILE=$2
fi
cat $1 | while read -u 0 FIRST LAST PART ; do
echo "firstname: '$FIRST'"
echo "lastname: '$LAST'"
echo "grade: '$PART'"
read -p "Exam grade: " -u 1 EXAM
#Edit
# was let FINAL=(PART+EXAM)/2
# should be:
FINAL=$(calc \($PART+$EXAM\)/2)
echo "$FIRST $LAST $PART $EXAM $FINAL" >> tmp
echo "final grade: '$FINAL'"
echo -e "-----------\n"
done
mv tmp $OUTFILE
But the shell arithmetic is integer only. For dividing you have two operators: /
(integer division) and %
(reminder). I think you should consider other language for the task like python
or perl
.
Edit:
You may want to use the calc
command from the apcalc
. See the corrected script above. You'll have to tweak the calc
command options to prevent it from taking over STDIN. Sorry I have to leave you with that - I have no time right now.
cat >
will read from keyboard to wherever you like - press ctrl+D to close input.
You can use the read
command to get user input from the user in shell script. For example
read data
echo $data
.
精彩评论