1

I have problem with deleting digit only elements from my string/array (conversion is easy) in bash. The trick is, in the array I have elements containing both digits and other character and I want to keep them.

So for

VAR="a2b a22 12b  417 900 600 86400 3600"

The output should be

"a2b a22 12b"

The furthest I could go is:

echo ${VAR}# |  sed 's/ [0-9][0-9]*[$ ]/ /g'

but it still doesn't solve the problem. I tried to do it in an array, but without "$" and "^" I'm not able to prevent deletion of some parts of "good elements".

Can anyone help me with that?

1
  • 1
    If your sequence of all digits always follows the mixed sequences, you could get by with the regular regex sed 's/ [^a-zA-Z][^a-zA-Z]*$//', but for a general solution, see John's answer below. Commented May 3, 2016 at 23:07

1 Answer 1

3

There are two issues with your code. One is that [$ ] will match a literal dollar sign but does, as one might hope, not match the end-of-the-line. The other is that, while g indicates global matching, the matches are not allowed to overlap which would be needed for it to work as you want.

If you have GNU sed, then a simple solution is to avoid matching the spaces and instead use \< and \> to mark word boundaries:

$ echo ${VAR} |  sed -E 's/\<[0-9][0-9]*\>/ /g'
a2b a22 12b     

Alternatively, without the GNU extensions, you can use looping:

$ echo ${VAR} |  sed 's/^[0-9][0-9]* / /; :a; s/ [0-9][0-9]* / /g; t a; s/ [0-9][0-9]*$/ /'
a2b a22 12b 

The code :a indicates a label. The code t a indicates a test. If the previous substitute command did make a substitution, then the sed jumps to label a.

(The above was tested under GNU sed. It should work with BSD/OSX sed with only minor adjustments.)

Sign up to request clarification or add additional context in comments.

1 Comment

I couldn't think of a better example to point out the benefits of boundaries in extended regex than this one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.