Reputation: 11
my condition always fails and causes it to go to the else statements.
Sample : Jame,Smith,12,100009,2 Jack, Smith-Potter,9,19998,5 Jaime-jane,smith,8,92384,3 I got it down to always keeping the most left first name if it's hyphenated and the most right if two last names. followed by grade, ID, and 2-5 must be replaced with a school. Such as 2 must change to HS, 3 to Middle school and so on. Its start from 2 to 5 and its store in school when the file is passed.
#!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
The condition fails and it skips to the else statement.
Upvotes: 0
Views: 51
Reputation: 246774
A lot of duplication in there. You can rely on a simple array lookup instead of 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
Upvotes: 0
Reputation: 4574
some corrections in your code :
Use -eq
instead of ==
if [[ $school -eq 2 ]]
Use this after your done :
done < <(echo "$1")
Your $NAME
var is not defined/declared
your $last_Name
var should be $Last_Name
Moreover you're better off using switch case statement :
case $school in
2) do_something ;;
3) do_smth_else ;;
4) ... ;;
esac
Upvotes: 1