views:

36

answers:

2

Suppose I have a string like this:

blah=-Xms512m

I want the output as 512.

I know I can get it using grep on Linux like this: echo $blah | grep -o -e [0-9]\\+ But this doesn't work on Solaris.

Any nice solutions so that it's compatible on both, Linux and Solaris? Or atleast on Solaris?

+2  A: 

I f you know the numbers will be together like that:

pax> echo 'blah=-Xms512m' | sed 's/[^0-9]//g'
512

It basically replaces all non-numeric characters with nothing. Of course, it won't do sensible stuff with:

pax> echo 'blah77=-Xms512m' | sed 's/[^0-9]//g'
77512

but, if you've only got one number it will work fine.

If you just need the first number, you can use:

pax> echo 'blah77=-Xms512m' | sed -e 's/^[^0-9]*//' -e 's/[^0-9].*$//'
77

For the last:

pax> echo 'blah77=-Xms512m' | sed -e 's/[^0-9]*$//' -e 's/^.*[^0-9]//'
512
paxdiablo
Excellent. Thanks a lot.
pavanlimo
+2  A: 

If you want to be completly brute-force, try using tr:

echo "blah=-Xms512m" | tr -c -d '[0-9]'
Chris J
+1. This solution too looks good. Thanks.
pavanlimo