Disclaimer: This is an imperfect solution. Perl's Scalar::Util::looks_like_number()
function may not be the best choice of routine for doing this. See StéphaneChazelas comments below.
I'm leaving it here if anyone wants to look at it and pick the coproc
bits out of it.
Rather than trying to craft your own regular expression to match the many possible floating point number format, use a library that already has implemented it:
perl -MScalar::Util -ne 'exit !Scalar::Util::looks_like_number($_)'
As a bash
shell function:
is_number () {
perl -MScalar::Util -ne 'exit !Scalar::Util::looks_like_number($_)' <<<"$1"
}
is_number hello && echo 'hello is a number'
is_number 1.234 && echo '1.234 is a number'
As a bash
co-process (to avoid starting up a Perl process for every time you want to test a number):
coproc PERLIO=:raw perl -MScalar::Util -ne \
'print Scalar::Util::looks_like_number($_) ? "Yes" : "No", "\n"'
while IFS= read -r -p 'Number please: ' possnum; do
printf '%s\n' "$possnum" >&${COPROC[1]}
read -u ${COPROC[0]}
case "$REPLY" in
Yes) printf '%s is a number\n' "$possnum" ;;
No) printf '%s is _not_ a number\n' "$possnum" ;;
esac
done
kill "$COPROC_PID"
Or combining the two:
coproc PERLIO=:raw perl -MScalar::Util -ne \
'print Scalar::Util::looks_like_number($_) ? "Yes" : "No", "\n"'
is_number () {
printf '%s\n' "$1" >&${COPROC[1]}
local REPLY
read -u ${COPROC[0]}
[ "$REPLY" = 'Yes' ] && return 0
return 1
}
while IFS= read -r -p 'Number please: ' possnum; do
if is_number "$possnum"; then
printf '%s is a number\n' "$possnum"
else
printf '%s is a _not_ a number\n' "$possnum"
fi
done
kill "$COPROC_PID"
grep -E '(\b\.\b|\b-\b)' yourfile
. Or after reading carefully a simplegrep '[.-]' filename
works – Valentin Bajrami Oct 12 '17 at 19:45255.255
is a valid float number, why did you write and ain't floating points ? – RomanPerekhrest Oct 12 '17 at 20:29This are possible floating points:
. What ispossible
? 2e-15 is not float at all.+.0009
neither so – Valentin Bajrami Oct 13 '17 at 19:52