Reputation: 11
I have a csv file that i am reading with a "while read" statement and i want to run an if statement on one of the fields in the csv.
====================================
csv file
client1,admin,password,5.9
client2,admin,password,5.8
====================================
this is my script
while read clientid user pass version
do
if [ '$version' = "5.9" ];
then
echo "IS"
else
echo "NOT"
fi
done < $1
The problem is that the if statement does not work.
It does not echo IS when the version is 5.9, it just keeps saying NOT, unless i change it to !=
I have tried using single and double quotes, even without... still doesn't work as expected.
The goal is to run commands until the end of the file. Is this script correct for doing this?
Obviously the IS and NOT would be replaced by actual command, this is just for testing.
Upvotes: 0
Views: 2859
Reputation: 5092
You can add the IFS
value comma and whitespace IFS=', '
. You will get the exact result.
#!/bin/bash
IFS=', '
while read clientid user pass version
do
if [ "$version" == "5.9" ] ; then
echo "IS"
else
echo "NOT"
fi
done < $1
Upvotes: 1
Reputation: 75548
And here's another:
while IFS=$' \t\r\n' read -r line; do
IFS=, read -r clientid user pass version __ <<< "$line"
if [[ $version == '5.9' ]]; then
echo "IS"
else
echo "NOT"
fi
done < "$1"
[[ ]]
over [ ]
. It doesn't do word splitting and pathname expansion.IFS=$' \t\r\n'
trims out leading and trailing spaces.__
is added to store surplus values just in case.Upvotes: 1
Reputation: 3646
The sample csv file provided has trailing whitespace on the line, which can be removed from the version
variable using parameter expansion.
This should work:
while IFS=, read -r clientid user pass version; do
if [ "${version//[[:space:]]/}" = "5.9" ]; then
echo "IS"
else
echo "NOT"
fi
done < $1
Upvotes: 1