Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

increase all array's indices by a number

There is an array:

bash-5.2$ arr=(a b c d e f)
bash-5.2$ paste <(printf "%s\n" "${!arr[@]}") <(printf "%s\n" "${arr[@]}")
0   a
1   b
2   c
3   d
4   e
5   f

I need to increase indices by 2 to get output:

2   a
3   b
4   c
5   d
6   e
7   f

Is there a way to easily increase all indices by two?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Assuming the objective is to renumber the array indices, one (brute force) idea:

$ arr=(a b c d e f)
$ arr2=(x x "${arr[@]}")
$ arr=("${arr2[@]}")
$ unset arr[0] arr[1]

$ paste <(printf "%s\n" "${!arr[@]}") <(printf "%s\n" "${arr[@]}")
2       a
3       b
4       c
5       d
6       e
7       f

$ typeset -p arr
declare -a arr=([2]="a" [3]="b" [4]="c" [5]="d" [6]="e" [7]="f")

Then again, if OP has the original statement for populating the array then just modify said statement, eg:

$ arr=(x x a b c d e f)
$ unset arr[0] arr[1]

$ paste <(printf "%s\n" "${!arr[@]}") <(printf "%s\n" "${arr[@]}")
2       a
3       b
4       c
5       d
6       e
7       f

$ typeset -p arr
declare -a arr=([2]="a" [3]="b" [4]="c" [5]="d" [6]="e" [7]="f")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading