bc - Multiply elements of array in bash -
i have 2 arrays
value={00..23} i=(01 02)
when multiply them using following command, results need format ... need result
00, 01...18, ...36
and get,
0,1 ..8, 18,..36 t=$(expr $value*$i | bc)
anybody can show me way?
and if want sum 24 @ value when second element of array days , 0 if first element of array days @ value...i have used following code without success...
#!/bin/bash data=`date +%y-%m-%d` data1=`date -d "1 day" +%y-%m-%d` days=("$data" "$data1") day in "${days[@]}"; value in {00..23}; # here order sum 00 if first day, , if second day, order sum 24 @ value... if [[ "$day"="${days[0]}" ]]; i=00 else i=24 fi t=$((10#$i+10#$value)) echo $t done done
i should 00, 01, 02...23, 24, 25, 26...48..but don't it....
your question isn't clear. guess you're in situation:
value=( {00..23} ) # <--- defines array, unlike code in question i=( 01 02 )
and want loop through arrays value
, i
, multiply terms. don't need expr
, bc
this, since you're dealing integers. catch is have leading 0
; have take care tell bash mean numbers in radix 10 (and not in radix 8), using radix specifier 10#
. also, deal formatting problem using printf
:
for in "${i[@]}"; b in "${value[@]}"; printf '%02d\n' "$((10#$a*10#$b))" done done
this print standard out following:
00 01 02 03 04 [...] 22 23 00 02 04 06 [...] 44 46
if want make new array out of these, proceed follows:
newarray=() in "${i[@]}"; b in "${value[@]}"; printf -v fab '%02d' "$((10#$a*10#$b))" newarray+=( "$fab" ) done done
then,
declare -p newarray
will show:
declare -a newarray='([0]="00" [1]="01" [2]="02" [3]="03" [4]="04" [5]="05" [6]="06" [7]="07" [8]="08" [9]="09" [10]="10" [11]="11" [12]="12" [13]="13" [14]="14" [15]="15" [16]="16" [17]="17" [18]="18" [19]="19" [20]="20" [21]="21" [22]="22" [23]="23" [24]="00" [25]="02" [26]="04" [27]="06" [28]="08" [29]="10" [30]="12" [31]="14" [32]="16" [33]="18" [34]="20" [35]="22" [36]="24" [37]="26" [38]="28" [39]="30" [40]="32" [41]="34" [42]="36" [43]="38" [44]="40" [45]="42" [46]="44" [47]="46")'
regarding edit: line
if [[ "$day"="${days[0]}" ]]; i=00
is wrong: need spaces around =
sign (otherwise bash tests whether string obtained expansion "$day"="${days[0]}"
not empty… , string never empty!—that's because bash sees one argument between [[...]]
). write instead:
if [[ "$day" = "${days[0]}" ]]; i=00
now, actually, script clearer (and shorter , more efficient) without hard-coded 24
, , without test each iteration of loop:
#!/bin/bash data=$(date +%y-%m-%d) data1=$(date -d "1 day" +%y-%m-%d) days=( "$data" "$data1" ) values=( {00..23} ) day in "${days[@]}"; value in "${values[@]}"; t=$((10#$i+10#$value)) echo "$t" done ((i+=${#values[@]})) done
Comments
Post a Comment