cut with field number specified by a variable ?

Associate
Joined
10 Nov 2004
Posts
2,237
Location
Expat in Singapore
Hi,

I am having problems getting a string (DB query results) delimited by a space in to an array in BASH.

ARRAY=$STRING results in all the SQL results going in to the arrays first element.
Trying to do a lop like ;
while [ "$INDEX" -lt "$ELEMENT_COUNT" ]
do
SQL_RETURN[$INDEX]=`echo $ELEMENTS | cut -d' ' -f$(INDEX)`
exit 0
done

brings an error for the cut command.

Ideas ? Must be an easy way but at 1:20am here my brain and eyes are fried :).

Cheers
RB
 
Hi,

I've got it sorted this morning although I am not quite sure what I did differently to last night.

Just needed to take the () out from around the variable used in the 'cut' statement, add one to the same variable as the array index starts at 0 and 'cut' fields start at 1, increment the INDEX variable at the end of the loop.

It works fine on my Solaris 8 test box at work so it should be fine for CentOS 5.4 when I get home.

I could have used awk or sed or could have just chopped the first element into a variable and then removed the first element from the data variable, that way I only need to keep removing 'cut -d' ' -f1' but it would appear to be much less elegant. I am sure there are better ways though :D.

Cheers
RB

Code just in case it may help anyone in the future.
#!/usr/bin/bash
declare -a SQL_RETURN
DATA="one two three four five six seven eight"
INDEX=0

ELEMENT_COUNT=`echo $DATA | wc -w`

while [ "$INDEX" -lt "$ELEMENT_COUNT" ]
do
FIELD=$((INDEX+1))
echo "Index: " $INDEX
echo "Field: " $FIELD
SQL_RETURN[$INDEX]=`echo $DATA | cut -d' ' -f$FIELD`
echo "Array value: " ${SQL_RETURN[$INDEX]}
INDEX=$((INDEX+1))
done
Output;
Index: 0
Field: 1
Array value: one
Index: 1
Field: 2
Array value: two
Index: 2
Field: 3
Array value: three
Index: 3
Field: 4
Array value: four
Index: 4
Field: 5
Array value: five
Index: 5
Field: 6
Array value: six
Index: 6
Field: 7
Array value: seven
Index: 7
Field: 8
Array value: eight
 
Back
Top Bottom