0

In bash, if an element in an array is found to contain a K, I want to multiply that element by 1000 and set that element to the product.

for i in "${stats_array[@]}"
do
        if echo "$i" | grep -q K; then
                # set that value to that value times 1000
        fi
done

How is this accomplished in a bash script?

My array might look like:

stats_array: 1, 54, 54K, 99

And I want it to look like:

stats_array: 1, 54, 54000, 99
0
4
$ { IFS=, ; arr=( 1,54,54K,99k ); }

$ printf '%s\n' ${arr[@]}
1    
54    
54K    
99k

## note: enable extended pattern matching for [...] with 'shopt -s extglob'
$ rearr=( "${arr[@]//%[Kk]/000}" )
$ printf '%s\n' ${rearr[@]}
1    
54    
54000    
99000

## or write the changes to same array
$ arr=( "${arr[@]//%[Kk]/000}" )

See also: How to add/remove an element to/from the array in bash?

0
1

Iterate over the indices of the array so it's easy to set the new value.

This uses case to branch on glob patterns, and you can see it's easy to extend this to M and G

stats_array=( 1 54 54K 99 )
for idx in "${!stats_array[@]}"; do
  value=${stats_array[idx]};
  case $value in
    *K) stats_array[idx]=$(( ${value%K} * 10**3 )) ;;
  esac
done
declare -p stats_array
declare -a stats_array=([0]="1" [1]="54" [2]="54000" [3]="99")

Note that bash arithmetic cannot handle floats, so you can't expect 53.9K to turn into 53900

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.