I have a array looking like this:

array=("(1 2 3) (123)" "2 31 (231)" "4 5 1 (451)" "(te)xt (1234)")

This array is a example. It does not look like this but its structure is the same (the strings have the same structure).
If I want to use the single strings in a select loop I can do it like this:

select string in "${array[@]}"
   # do something

But the string in the parentheses is not for display. So I used sed to remove them:

echo "${array[@]}" | sed -r 's/ \([0-9]+\)$//g'

This did not work. Only the last parentheses were removed and the strings have been merged together. But how can I achieve the desired result which would be the same as the following example:

array2=("(1 2 3)" "2 31" "4 5 1" "(te)xt")

select string in "${array2[@]}"
   # do something

Arrays have no meaning to sed. Once your bash array is passed through sed, becomes plain text.

Use bash to remove the parenthesis (supposing the part to remove is always at the end of the strings):


(In you bash manual check the section about parameter expansion for more.)

| improve this answer | |
  • This very nice. But if the first part of the string is also in parentheses then the entire string gets emptied. – BrainStone Dec 22 '13 at 17:01
  • Updated my answer. – manatwork Dec 22 '13 at 17:06
  • That's exactly what I was looking for. Thank you! – BrainStone Dec 22 '13 at 17:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.