Here is the task: 1. move all array elements to offset (index) 'off'. I.e. such, that first array element will be at index 'off'. 2. make holes (sequences of unset elements) in the array by moving different array parts to different offsets (indexes) off1, off2, off3,.. . This can't be done by arr=( [i]="${arr[@]}" ) because "${[@]}" expansion works not as it should: it treats assignment prefix specially, and in such case works the same as "${[*]}". So, we should use some workaround, like #!/bin/bash declare -a arr=( 1 2 3 4 5 ) declare -i off=15 declare -p arr b=${arr[0]} unset arr[0] arr=( [off]=$b "${arr[@]}" ) declare -p arr This can be done simplier, but i'm not sure which version of bash this requires #!/bin/bash declare -a arr=( 1 2 3 4 5 ) declare -i off=15 declare -p arr arr=( [off]=${arr[0]} "${arr[@]:1}" ) declare -p arr Second task can be solved like this #!/bin/bash declare -a arr=( 1 2 3 4 5 6 7 8 9 10 11 12 13 ) declare -i off1=15 len1=2 i1=0 declare -i off2=21 len2=3 i2=$((i1 + len1)) declare -i off3=40 len3=4 i3=$((i2 + len2)) declare -i off4=70 i4=$((i3 + len3)) declare -p arr arr=( [off1]=${arr[i1]} "${arr[@]:i1 + 1: len1 - 1}" [off2]=${arr[i2]} "${arr[@]:i2 + 1: len2 - 1}" [off3]=${arr[i3]} "${arr[@]:i3 + 1: len3 - 1}" [off4]=${arr[i4]} "${arr[@]:i4 + 1}" ) declare -p arr Note, that all existed holes in the array after such operations would be lost.
DISCLAIMER. English language used here only for compatibility (ASCII only), so any suggestions about my bad grammar (and not only it) will be greatly appreciated.
четверг, 16 декабря 2010 г.
[bash] Move array elements
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий