Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
   # do something
done

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
   # do something
done
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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):

array2=("${array[@]%(*}")

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

share|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

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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