0

In bash script I am taking command line input in alphanumeric values. example: D7, 12D I want to assign these value to some variable but I want only numeric values to be assigned. In above example value should be assigned as 7 and 12

In linux it can be done by

echo "D7" |grep -o '[0-9]*'

I want this should work for both linux,unix servers. Above command doesnt work on solaris box.

Thanks for help

~Ankit

2
  • 1
    You want GNU grep. The only reason Oracle doesn't change it (AFAIK), is because it would break existing Solaris behavior. Next, try it on AIX, HP-UX, the BSD(s) and Minix. Good luck! Commented Oct 2, 2017 at 16:51
  • Are the letters always confined to a suffix or prefix, or could you get a value like 14D7, in which case should that be treated as 14, 7, or 147? Commented Oct 2, 2017 at 16:55

1 Answer 1

2

While this doesn't directly answer your question about grep in different environments, you can use sed for this:

echo "D7"  | sed 's/[^0-9]//g'

s/[^0-9]//g says "Replace any thing that isn't a number with nothing"

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

2 Comments

Well, sure; you could also do that. But OP was asking about grep behavior not being consistent. :)
@ElliottFrisch Oh! I didn't read that far. I always got in trouble in school for not reading all of the instructions before jumping into the solution. I feel like I should leave this up here since sed may provide an alternate to the oddball implementations of grep in solaris and all that.

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.