0

I have such array:

Array={123},{456}

Now I want to delete the last item 6.

  • 1
    To remove last element in array you can use unset Array[6] for 7th element or unset Array[-1] for the last. But are you sure that is the array? – Costas Jan 21 '15 at 11:38
  • This sounds like an XY problem. However, sed 's/.}$/}/' <<< "$Array" – glenn jackman Jan 21 '15 at 12:11
5

Arrays in bash are defined like:

a=(foo bar baz)

Or:

a=([12]=foo [5]=bar)

(arrays in bash are more like associative arrays with keys limited to positive numbers and with elements sorted on those numerically).

To delete the last character of the element with the greatest key, with recent versions of bash, you'd do:

a[-1]=${a[-1]%?}
| improve this answer | |
1

It is not an array, it is just a variable named Array. To remove next to last character of that variable you can play with substring expansion, e.g.:

$ Array={123},{456}
$ echo "${Array:0:${#Array}-2}${Array:${#Array}-1}"
{123},{45}

Here ${#Array} denotes number of characters of the variable string.

| improve this answer | |
  • 1
    Alternatively just "${Array::-2}}" – StrongBad Jan 21 '15 at 11:39
  • Other variant with variable if element is unique: ${Array/${Array: -2:1}/}. In modern bash version: ${Array:0:-2}${Array: -1}. Don't miss spaces – Costas Jan 21 '15 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy