0

我有以下数据,我从 CSV 逗号分隔文件中读取,它包含 8 列: ID、名称、主题、Grade1、Grade2、Grade3、Grade4、Grade5、Final

以下是数据示例:

1,Allan Wilkinson,Calculo I,3.4,2.5,5,5,3.2
1,Allan Wilkinson,Calculo II,1,4.1,3.5,3.7,2.7
1,Allan Wilkinson,Fisica I,3,3.2,3.7,4.2,5
2,Rexanne Dickinson,Fisica II,4.3,3.4,2.5,5,3.5
2,Rexanne Dickinson,Estadistica,2.3,1,4.1,3.5,5
2,Rexanne Dickinson,Calculo I,3.4,2.5,5,3.7,3.5
3,Meaghan Neely,Calculo II,1,4.1,3.5,2.5,5
3,Meaghan Neely,Fisica I,3,3.2,3.7,4.1,3.5
3,Meaghan Neely,Fisica II,4.3,2.1,2.5,4.5,3.2
4,Ariana Donkin,Estadistica,1,4.1,4.3,2.1,2.5
4,Ariana Donkin,Calculo I,3,3.2,1,4.1,4.1
4,Ariana Donkin,Calculo II,3.4,3.2,1,4.1,3.2
5,Camron Jenner,Fisica I,2.1,2.5,5,2.5,2.5
5,Camron Jenner,Fisica II,4.1,4.1,3.5,4.1,4.3

我正在尝试编写一个 Bash 程序,用户可以在其中输入新行或更新当前行,并将数据保存到 CSV 文件中。

我目前拥有的代码读取并匹配请求的数据,并要求提供新数据。我试图实现 awk 但我不确定如何去做,或者它是否真的可以完成这项工作。

这是代码:

echo "Enter the student ID";
read student;

while IFS=, read -r ID name subject grade1 grade2 grade3 grade4 grade5 finalg
do
if [[ $ID == $student ]]; then
echo "$subject $grade1 $grade2 $grade3 $grade4 $grade5 $finalg";
fi
done < grades.csv

echo "Enter Subject to Modify or Enter a New one to Add";
read modSubject;

echo "Enter Grade1";
read grade1new;

echo "Enter Grade2";
read grade2new;

echo "Enter Grade3";
read grade3new;

echo "Enter Grade4";
read grade4new;

echo "Enter Grade5";
read grade5new;

total=$(echo "$grade1new + $grade2new + $grade3new + $grade4new + $grade5new" | bc);
final=$(echo "scale=2; $total/5" | bc);

有人可以指出我正确的方向。谢谢

4

1 回答 1

0

你快到了:-)

#!/bin/bash

echo "Enter the student ID";
read student;

while IFS=, read -r ID name subject grade1 grade2 grade3 grade4 grade5 finalg
do
    if [[ "$ID" = "$student" ]]; then
        echo "$subject $grade1 $grade2 $grade3 $grade4 $grade5 $finalg"
        snm="$name"  # <-we need the name so we store it here, safe 
    fi
done < grades.csv

echo "Enter Subject to Modify or Enter a New one to Add"; read modSubject;
echo "Enter Grade1"; read grade1new;
echo "Enter Grade2"; read grade2new;
echo "Enter Grade3"; read grade3new;
echo "Enter Grade4"; read grade4new;
echo "Enter Grade5"; read grade5new;

total=$(echo "$grade1new + $grade2new + $grade3new + $grade4new + $grade5new" | bc);
final=$(echo "scale=2; $total/5" | bc);

#drop the old record
grep -v "^$student,$snm,$modSubject," grades.csv >tmp$$

#add the new record
echo "$student,$snm,$modSubject,$grade1new,$grade2new,$grade3new,$grade4new,$grade5new,$final" >>tmp$$ 
mv tmp$$ grades.csv

您只需要两个小改动。第一个是 while 循环中的一个小改动,因为我们需要名称。最后是删除旧记录(如果存在)并添加新记录。输出未排序。如果要对其进行排序,只需sort grades.csv -o grades.csv在末尾添加即可。

当然可以对其进行一些优化,但我不想对您的代码进行太多修改:-)

于 2013-11-12T04:25:15.323 回答