jl66
asked on
Assign ksh array value incorrectly
Have a ksh script below:
cat s.ksh
#!/bin/ksh
_COMB=";B;;D;"
set -A arr $( echo ${_COMB} | awk -F";" '{print $1, $2, $3, $4. $5}' )
for i in (0..5)
do
if [[ "x${arr[$i]}" = "x" ]]; then
${arr[$i]}=' '
fi
echo "=${arr[$i]}="
done
When running it, expect to get the following:
= =
=B=
= =
=D=
= =
But I got the different results. Can any gurus shed some light on it? Can it be simplified? I need the array with data for late use.
cat s.ksh
#!/bin/ksh
_COMB=";B;;D;"
set -A arr $( echo ${_COMB} | awk -F";" '{print $1, $2, $3, $4. $5}' )
for i in (0..5)
do
if [[ "x${arr[$i]}" = "x" ]]; then
${arr[$i]}=' '
fi
echo "=${arr[$i]}="
done
When running it, expect to get the following:
= =
=B=
= =
=D=
= =
But I got the different results. Can any gurus shed some light on it? Can it be simplified? I need the array with data for late use.
The problem is with this statement:
So awk gets only two fields, B and D.
and arr[0]=B, arr[1]=D, and arr[2] through arr[4] are empty.
_COMB=";B;;D;"
There is an empty string before the B, between B and D, and after D.So awk gets only two fields, B and D.
and arr[0]=B, arr[1]=D, and arr[2] through arr[4] are empty.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks a lot for everyone's tips/solutions. Various solutions from the gifted gurus.
Can the following array assignment include the "if" statement to add one space if a specific elment of the array is null?
eval $(echo ${_COMB} | awk -F";" '{for(i=1;i<=NF;i++) print "arr["(i-1)"]=\""$i"\""}')
Can the following array assignment include the "if" statement to add one space if a specific elment of the array is null?
eval $(echo ${_COMB} | awk -F";" '{for(i=1;i<=NF;i++) print "arr["(i-1)"]=\""$i"\""}')
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks a lot. Appeciate everyone's contribution. Finally got exactly what was wanted within one line.
Correct assignment
Var='data'
echo $Var
$Var='data'
echo $Var
You will get the result you have.
Note your array assignment into arr
I think your array access is not correct $arr[0] your ${arr[0]} I think is not correct.