Hi
Do you have any pointers how to validate numbers (not to contain alphabets and special characters) and date(MM/DD/YYYY) format.
I used following regular expression to validate integer, which is not working in the default shell:
nodigits="$(echo $testvalue | sed 's/[[:digit:]]//g')"
if [ ! -z $nodigits ] ; then
echo "Invalid number format! Only digits, no commas, spaces, etc." >&2
return 1
fi
Thanks
Alok
I'd use grep
$ echo "12/31/2004" | grep '^[0-1][0-9]/[0-3][0-9]/[0-9]\{4\}$' >/dev/null 2>&1
$ echo $?
0
$ echo "some text" | grep '^[0-1][0-9]/[0-3][0-9]/[0-9]\{4\}$' >/dev/null 2>&1
$ echo $?
1
You can then check $? and act accordingly.
You can extend this example to simple numerical verification...
$ echo "193912391293" | grep '^[0-9]*$'
You get the idea....
Cheers
ZB
What happens when you use this command?
echo "12/31/2004" | grep '^[0-1][0-9]/[0-3][0-9]/[0-9]\{4\}$' >/dev/null 2>&1
I used it but did not use echo $? afterword and now I'm afraid to use it on /dev/null again.
I actually used the above command but replaced the /dev/null with Test1 a file in my test directory. It erased everything in that file and replaced it with 12/31/2004.
What can I do about my /dev/null? I don't what that to be erased. But also with my test file I wanted to change the format of the date for every occurance of 12-31-2004 or 12/31/2004 to 2004-31-12 would the above command work on that with a little more tweaking?
thanks in advance!
Don't worry about damaging /dev/null - unless you're logged in as root and issue rm /dev/null nothing bad will happen!
The > redirection operator will erase anything in a file before outputting to it - use >> if you want to append.
If you want to change the format to delimit the date components with "-" just change the command to
echo "12-31-2004" | grep '^[0-1][0-9]-[0-3][0-9]-[0-9]\{4\}$' > myfile # or wherever
If you had the date in a variable, say DATE, then you can check the format of DATE with
echo "$DATE" | grep '^[0-1][0-9]-[0-3][0-9]-[0-9]\{4\}$' > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "Date correctly formatted"
else
echo "Date incorrectly formatted"
fi
If you have a something along the lines of
DATE="12/31/2004"
and you want to change the format, try
echo "$DATE" | grep '^[0-1][0-9]/[0-3][0-9]/[0-9]\{4\}$' > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "Date correctly formatted"
echo "$DATE" | tr '/' '-'
else
echo "Date incorrectly formatted"
fi
And the "/" will be substituted for "-"
If this isn't what you want please post exact requirements.
Cheers
ZB
Thank You so much for the quick reply.
And thank God I wasn't root today.
Anyway, the code looks like it will work
but I haven't tried it yet.
I'll let you know what happens.