A grep
solution:
$ echo "2.5 test. test -50.8" | tr ' ' '\n' | grep -E '^[+-]?[0-9]*\.?([0-9]+)$'
2.5
-50.8
The tr
just converts the line into multiple lines by replacing the spaces with newlines.
The grep
command looks for strings that starts with an optional +
or -
, possibly followed by some digits and an optional decimal point. Then we require some digits at the end.
This will let through things like 00000123.91288000
, which just looks strange. Is this a number we want to filter out or not? It's technically a floating point number, just oddly formatted.
EDIT: To properly check for numbers, do not write your own regular expression! Use a library routine from somewhere reliable.
In my case, I would use Perl's Scalar::Util
package, which has a convenient looks_like_number()
subroutine:
$ echo "2.5 test. test -50.8" | tr ' ' '\n' | perl -MScalar::Util -ne 'Scalar::Util::looks_like_number($_) && print'
2.5
-50.8
This has the added benefit of finding numbers on other forms, such as 1e3
.