How to validate the following file content?
That should be include single integer/float number by bash Regular Expression or any other idea with awk/sed.
example:
cat /var/VERSION/Version_F35_project_usa
2.8
If you want to check that the file as a whole contains a number of decimal digits, optionally followed by a .
and more digits and then an optional newline character, you could do:
is_valid() {
awk 'END{exit(!(NR == 1 && /^[0-9]+(\.[0-9]+)?$/))}' < "$1"
}
if is_valid /var/VERSION/Version_F35_project_usa; then
echo the file has the right kind of content
else
echo >&2 the file does not have the right kind of content
fi
+2
or -25
, rejects ` 1.3` and accepts as valid 0000.00
. Not to mention 1,345,234.75434
, 1.345.234,75434
or 1e3
.
awk
implementations it could give false positives on things like 1<NUL>whatever
.
Aug 15, 2017 at 10:07
+25
is an integer, as is 1e3
and ` 1.3` seems to me to match a float. So: no, your regex does not match what was asked, only a limited solution to some parcial view of the problem.
Use grep
, if matched means that's valid:
grep -P '^[0-9]+(\.[0-9]+)?$' infile.txt
The above regex can be used in sed
or awk
or any command.
sed -n -Ee '/^[0-9]+(\.[0-9]+)?$/p'
awk '/^[0-9]+(\.[0-9]+)?$/'
Here is also checking if file match with this regex or not.
awk '/^[0-9]+(\.[0-9]+)?$/{print "matched";exit} {print "not-matched";exit}' file
104.23
, as 0.0
, also 0.
and plain 0
.
'^[0-9]+\.?([0-9]+)?$'
, by the way I don't think so x.
is considering valid by OP's question even in edit history I did this but I fixed to don't match x.
perl
specific in the first grep
one, so you could do grep -xE '[0-9]+(\.[0-9]+)?'
to make it standard/portable. See also sed '/^[0-9]\{1,\}\(\.[0-9]\{1,\}\)\{0,1\}$/!d'
for a standard/portable equivalent of your sed
one.
Aug 15, 2017 at 10:16
1.2
,-1.2
variations? Or something that looks more like a version number like 1.2.3, 1.2pre2, 1.2-3, 12.2a... Should the locale's decimal separator (.
or,
) be honoured?