I have an input text file looking like:
# string name | String type (x,y,or z)
name_1 | x
name_2 | y
name_3 | z
I want to read it and fill
- A global array containing all the string names
- Three arrays (say list_x, list_y and list_z) depending on the string type
Here is my script:
# Array initialization
list_global=();list_x=();list_y=();list_z=()
# Remove blank lines if there are some
sed -i '/^[[:space:]]*$/d' input_tab.txt
# Reading file
while read line
do
name=$(echo $line |awk -F "|" '{print $1}'|sed 's/ //g')
type=$(echo $line |awk -F "|" '{print $2}'|sed 's/ //g')
# Checking data are correctly read
printf "%6s is of type %2s \n" "$name" "$type"
# Appending to arrays
list_global+=("$name")
if [ "$type"==x ]
then
list_x+=("$name")
elif [ "$type"==y ]
then
list_y+=("$name")
elif [ "$type"==z ]
then
list_z+=("$name")
fi
done < input_tab.txt
# Print outcome
echo global_list ${list_global[@]}
echo -e "\n \n \n "
echo list_x ${list_x[@]}
echo list_y ${list_y[@]}
echo list_z ${list_z[@]}
This produces the following output
name_1 is of type x
name_2 is of type y
name_3 is of type z
global_list name_1 name_2 name_3
list_x name_1 name_2 name_3
list_y
list_z
Meaning my input file is correctly read, and the way I fill arrays is valid. I can not get to understand why it would systematically satisfy the first "if" it goes through. If I first test if [ "$type"==z ] then everything goes to list_z.
Notes:
- Using a switch/case instead of if leads to the same result
- I run bash 4.1.2
Any help/explanation would be much appreciated, Thanks in advance