我的条件总是失败,并使它进入else语句。
样本:Jame,Smith,12,100009,2 杰克,史密斯-波特,9,19998,5 史密斯(Jaime-Jane),8,92384,3 我将其归结为始终保留最左边的名字(如果带有连字符)和最右边的(如果两个带有姓氏)。其次是年级,ID和2-5,必须更换为学校。如2必须更改为HS,3必须更改为中学等等。该文件从2到5开始,并且在文件通过后存储在学校中。
#!bin/bash
OLDIFS=$IFS
IFS=","
while read First_Name Last_Name Grade Student_Id school
do
#Keeps the first name before "-"
FIRSTNAME=$(echo $First_Name | cut -d'-' -f 1)
#Keeps most left name
NAME=$(echo $FIRSTNAME | cut -d" " -f 1)
#Find the spaces between last name and if there are more than one space
it makes it into one space.
LASTNAME=$(echo $Last_Name | sed -e 's/ */ /g')
other=$(echo $LASTNAME | cut -d' ' -f 2)
last_Name=$(echo $other | cut -d'-' -f 2)
if [ $school == 2 ]
then
School=$(echo $school | sed -e 's/2/HS/g')
echo "$NAME"."$last_Name" "$NAME" "$last_Name" "$Grade"thGrade
"$Student_Id" "$School"
elif [ $school == 3 ]
then
School=$(echo $school | sed -e 's/3/MI/g')
echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..."
"$Student_Id" "$School"
elif [ $school == 4 ]
then
School=$(echo $school | sed -e 's/4/MO/g')
echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..."
"$Student_Id" "$School"
else
School=$(echo $school | sed -e 's/5/K/g')
echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..."
"$Student_Id" "$School"
fi
done < $1
IFS=$OLDIFS
条件失败,并跳至else语句。
答案 0 :(得分:1)
您的代码中的一些更正:
使用-eq
代替==
if [[ $school -eq 2 ]]
完成后使用它:
done < <(echo "$1")
您的$NAME
变量未定义/声明
您的$last_Name
变量应为$Last_Name
此外,最好使用switch case语句:
case $school in
2) do_something ;;
3) do_smth_else ;;
4) ... ;;
esac
答案 1 :(得分:0)
里面有很多重复。您可以依靠简单的数组查找来代替echo|sed
#!bin/bash
schools=("" "" HS MI MO K) # don't need index 0 or 1
while IFS="," read -r First_Name Last_Name Grade Student_Id school
do
case "$school" in
[2-5]) School=${schools[$school]}
echo "$NAME"."$last_Name" "$NAME" "$last_Name" Class"..." "$Student_Id" "$School"
;;
*) echo "Unknown school: $school"; ;;
esac
done < $1