Reputation: 61
I'm new on bash programming and actually I didn't find an answer for my topic among the ones just answered.
I got a variable with a list of timestamp values, such as
myvar="16:00:01 17:30:00 18:13:12"
What I've to do is to fill an array list with each single timestamp. Right now what I'm doing (and it works) is:
varlist[0]=$(echo $myvar | awk '{$NF = "" ; print $1}')
varlist[1]=$(echo $myvar | awk '{$NF = "" ; print $2}')
varlist[2]=$(echo $myvar | awk '{$NF = "" ; print $3}')
The problem is that putting everything in a for loop like the following, it doesn't give me the single item timestamp but the entire string.
for (i=1 ; i<=3; i++)
do
varlist[$i]=$(echo $myvar | awk '{$NF = "" ; print $i}')
done
How can I loop the awk?
Upvotes: 2
Views: 1516
Reputation: 67319
for (i=1 ; i<=3; i++)
do
varlist[$i]=$(echo $myvar | awk -v myi=$i '{$NF = "" ; print $myi}')
done
Upvotes: 1
Reputation: 51693
The problem is that You are tring to use an outside variable (namely: "$i
") inside Your awk script with single quotes. It (those single quotes) does not allow to interpret the variable.
You can do it this way (if You want to do it with awk, but there are other ways - look up bash array docs).
for (i=1 ; i<=3; i++)
do
varlist[$i]=$(echo $myvar | awk -v CNTR=$i '{print $CNTR}')
done
Upvotes: 0
Reputation: 786289
You can create an array in bash directly like this:
array=($myvar)
then:
# print # of elements in array
echo ${#array[@]}
# print all the elements in array
echo ${array[@]}
# loop thru your array
for i in ${array[@]}; do
echo "i=$i"
done
Upvotes: 4