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

Print array elements from index k

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:]}"

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 :

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 ((...))
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