1

I have such array:

Array={123},{456} 

Now I want to delete the last item 6.

2
  • 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
    CommentedJan 21, 2015 at 11:38
  • This sounds like an XY problem. However, sed 's/.}$/}/' <<< "$Array"CommentedJan 21, 2015 at 12:11

2 Answers 2

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]%?} 
    2

    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.

    2
    • 2
      Alternatively just "${Array::-2}}"
      – StrongBad
      CommentedJan 21, 2015 at 11:39
    • 1
      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
      CommentedJan 21, 2015 at 11:49

    You must log in to answer this question.