If I store a date in a variable, how can I verify that it is in the correct format? For example if the variable temp1 contains 20011010, how can I be sure that the variable contains 8 characters, and that they are all digits.
It would be better to know a) what shell you are running b) where the date comes from c) where it's going.
You could do it with a quick awk script like so
read var
echo $var|awk '{ flag $0 }
{ if ( length($0)!=8){ flag = "INVALID"
{ for ( i = 1;i <= length($0);i++)
if( substr($0,i,1)<0 || substr($0,i,1)>9){flag = "INVALID"}
{print flag}'|pg
If you wanted better date testing ( i.e. valid month, day etc. ) something a bit more complex would need to be written.
There are possibly easier ways to do this, if anyone knows any, I'd be interested too. SOL
The best thing about banging your head against a wall is when you stop.
Sorry I appear to have lost an equal sign the line
echo $var|awk '{ flag $0 }
should be
echo $var|awk '{ flag = $0 } SOL
The best thing about banging your head against a wall is when you stop.
a) what shell you are running
Kornshell
b) where the date comes from
the user types in the date
c) where it's going.
It's compare against the system date
The above script should work with any shell. I used awk as you didn't specify a shell environment. Here's the modified script, it takes an input date into the variable var and outputs it into variable var2, which you should then be able to test. Invalid dates will pass out the value INVALID which you should be able to test within the main body of the script. If you need any further help or you require further validation, please enclose relevant section of the script.
read var
echo $var|awk '{ flag = $0 }
{ if ( length($0)!=8){ flag = "INVALID"}}
{ for ( i = 1;i <= length($0);i++)
if( substr($0,i,1)<0 || substr($0,i,1)>9) {flag = "INVALID"}}{print flag}' | read var2 SOL
The best thing about banging your head against a wall is when you stop.
You could also carry out some rudimentary testing with the following.
read var
echo $var|awk '{ flag = $0 }
{ year = substr($0,1,4)}
{ month = substr($0,5,2)}
{ day = substr($0,7,2)}
{ if ( length($0)!=8){ flag= "INVALID"}}
{ if (year < 1999 || year > 2001 ){ flag = "INVALID"}}
{ if (month < 1 || month > 12 ){ flag = "INVALID"}}
{ if (day < 1 || day > 31 ){ flag = "INVALID"}}
{print flag}' | read var2
SOL
The best thing about banging your head against a wall is when you stop.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.