A
A
Asya2021-08-30 23:35:45
bash
Asya, 2021-08-30 23:35:45

How to slice an array in bash?

I'm trying to slice my array from j to j+6
but when j increases by 6, my array doesn't slice properly:

array=( a b c d e f g h i j k l m n o p q r s t u v w x w z a b c d e f g h i j k )
j=0
while true
do
        for i in ${array[@]:$j:$((j+6))}
        do
                echo ${array[@]:$j:$((j+6))}
                j=$(($j+6))
                echo $j
        done
done


it turns out like this:

a b c d e f
6
g h i j k l m n o p q r
12
m n o p q r s t u v w x w z a b c d
18
s t u v w x w z a b c d e f g h i j k
24
w z a b c d e f g h i j k
30
e f g h i j k
36
k
42


and it should be like this:

a b c d e f
6
g h i j k l 
12
m n o p q r 
18
s t u v w x 
24
w z a b c d 
30
e f g h i j 
36
k
42

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2021-08-31
@asyaevloeva

my array is slicing the wrong way

after the second colon comes the length and not the index. Those. should be echo${array[@]:$j:6}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question