Reputation: 403
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?
Upvotes: 1
Views: 24
Reputation: 113924
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.)
Upvotes: 3