Skip to main content
3 of 4
added 202 characters in body
Tim
  • 106.8k
  • 234
  • 650
  • 1.1k

Duplicate elements of an array except the first and last elements

I have an array, and I would like to repeat each element except the first and last elements.

For example if the array has five elements 1 2 3 4 5, then after repeating, its elements should be 1 2 2 3 3 4 4 5.

My bash commands are

$ newarr=("${myarr[0]}")
$ for i in $(seq 1 $((${#myarr[@]}-2))) ; do newarr+=( "${myarr[i]}" "${myarr[i]}"); done
$ newarr+=("${myarr[-1]}")

Is there a more clear way than mine?

I am also wondering about how to wrap that into a function which takes myarr as argument, and returns newarr. (After creating such a function, I will read an array from a file, so that each element stores a line in the file, and then call the function on the array. If creating such a function is not a good approach, let me know.)

Thanks.

Tim
  • 106.8k
  • 234
  • 650
  • 1.1k