Score:0

Print array elements from index k

jp flag

I have a bash array and want to print the array elements starting from index k.

Things did not work out with the following strategy.

printf "%s\n" "${ar[$j:]}"
cocomac avatar
cn flag
Why not just use a `for` loop?
Score:1
hr flag

The syntax is ${ar[@]:j}1. From the Parameter Expansion section of man bash:

   ${parameter:offset:length}
   .
   .
   .
          If parameter is an indexed array name subscripted by @ or *, the
          result is the length members of the array beginning  with  ${pa‐
          rameter[offset]}.   A  negative  offset is taken relative to one
          greater than the maximum index of the specified array.  It is an
          expansion error if length evaluates to a number less than zero.

So given

$ ar=("1" "2 3" "4" "5 6" "7 8" "9")

then (remembering that bash array indixing is 0-based):

$ j=3; printf '%s\n' "${ar[@]:j}"
5 6
7 8
9

Alternatively, use a C-style for loop:

for ((i=k;i<${#ar[@]};i++)); do
  printf '%s\n' "${ar[i]}"
done

  1. or ${ar[@]:$j} if you prefer - the second $ is optional, since the indices are evaluated in a numerical context similar to ((...))
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.