If you don’t have arrays…but you have awk

A small project I have in the embedded side of things requires keeping track of information per index, what one would normally do in an array. However, the ash shell from busy box does not support arrays. Busybox does support awk. The following function is used to increment, decrement, and reset and array of counters of single digits stored as characters in a string.

#mod_field takes three parameters: OP INDEX DATA

#OP is the opperation: inc, dec, reset

#INDEX is the offset into the string from 1 to 9

#DATA is the state stored as a string

#OUTPUT is DATA with DATA[INDEX] modified

mod_field(){
OP=$1
INDEX=$2
DATA=$3

echo $OP $INDEX $DATA | \
awk ‘
{
VAL=substr($3,$2,1);
FIRST=substr($3,0,$2-1);
TAIL=substr($3,$2+1) ;
}
$1 ~ /inc/ { VAL++; }
$1 ~ /dec/ { VAL–; }
$1 ~ /reset/{ VAL=0; }
END{ print FIRST VAL TAIL;}

}

#Here is how to call it:
DATA=0000000000
DATA=`mod_field inc 3 $DATA `
echo $DATA

#This should produce 0010000000

DATA=`mod_field dec 3 $DATA `
echo $DATA

#And set DATA back to 0000000000
for i in 1 2 2 3 4 4 4 4 5 6 6 7 8 8 8 8 8 8 9
do
DATA=`mod_field inc $i $DATA `
done
echo $DATA
#Should produce 1214121610

for i in 1 2 2 3 4 4 4 4 5 6 6 7 8 8 8 8 8 8 9
do
DATA=`mod_field dec $i $DATA `
done
echo $DATA

#Should produce 0000000000

DATA=1111111111111
DATA=`mod_field reset 3 $DATA`
echo $DATA

#Should produce 0000000000

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.