check for numeric content in a shell script (FreeBSD sh)
parv at pair.com
parv at pair.com
Thu Jun 24 18:31:01 UTC 2010
in message <87d3vgmj1s.fsf at cjlinux.localnet>,
wrote Carl Johnson thusly...
>
> Carl Johnson <carlj at peak.org> writes:
>
> > Carl Johnson <carlj at peak.org> writes:
> >
> >> vogelke+unix at pobox.com (Karl Vogel) writes:
> >>
> >>>>> On Thu, 24 Jun 2010 09:24:39 +0800,
> >>>>> Aiza <aiza21 at comclark.com> said:
> >>>
> >>> A> Receiving a variable from the command line that is suppose
> >>> A> to contain
> >>> A> numeric values. How do I code a test to verify the content
> >>> A> is numeric?
> >>>
> >>> The script below will work with the Bourne or Korn shell.
> >>> Results for "0 1 12 1234 .12 1.234 12.3 1a a1":
> >>>
> >>> 0 is numeric
> >>> 1 is numeric
> >>> 12 is numeric
> >>> 1234 is numeric
> >>> .12 is numeric
> >>> 1.234 is numeric
> >>> 12.3 is numeric
> >>> 1a is NOT numeric
> >>> a1 is NOT numeric
> >>
> >> You might want to try testing "123..45".
> >> I tried changing:
> >>> if expr "$arg" : "[0-9]*[\.0-9]*$" > /dev/null
> >> to:
> >> if expr "$arg" : "[0-9]*\.*[0-9]*$" > /dev/null
> >> but it still claims that it is numeric, so *I* must be missing
> >> something.
> >
> > I just realized that I had a stupid mistake there and should
> > have used:
> > if expr "$arg" : "[0-9]*\.[0-9]*$" > /dev/null
> And of course that was another stupid mistake that I didn't test
> properly. I really wanted 0 or 1 decimal points, so I wanted
> '\.\?', except that FreeBSD expr doesn't recognize '\?'. I
> finally ended up with the following which seems to work as *I*
> expected it to work:
> if expr "$arg" : "[1-9]*\.\{0,1\}[0-9]*$" > /dev/null
That regex considers "." a number but not "0.9" (this one seems to
be due to typo) nor a negative number.
I would personally to use egrep or awk (printf "%s" "${arg}" | egrep
"${regex}" [0]) instead of expr.
- parv
[0] Compact regex ....
# Matches a number, either positive (without '+' sign) or
# negative, which is either a whole number; or a real number
# ending with decimal point, or a real number with or without
# leading digits before the decimal point.
^
-?
(
[0-9] [.]? [0-9]*
|
[0-9]? [.] [0-9]+
)
$
...by removing whitespace before use.
--
More information about the freebsd-questions
mailing list