The UNIX and Linux Forums  


Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #4 (permalink)  
Old 11-17-2008
jim mcnamara jim mcnamara is online now Forum Staff  
...@...
  
 

Join Date: Feb 2004
Location: NM
Posts: 5,793
That was in lieu of this, dates are messy

Code:
echo $filename | \
 sed  's/\(^[1-2][0-9]\{3\}\)-\([0-1][0-9]\)-\([0-3][0-9]\)-\([A-Z_0-9a-z]*\)/\4/'  | read newfilename
if [[ ! -z newfilename ]] ; then
   filename=$newfilename
fi

Basically I would suggest that naming every file with a leading date has problems. try
ls -l instead. Chris was technically correct -no doubt - but the usefulness of the above is limited. In part this is due to the way dates are constructed - and the above regex is not perfect. It will think 2008-19-19 is a date - which it is not. Most correct date regexes are several hundred character long. The only gold standard is to refer to the output of cal.


We use part of this date check algorithm below (simplified greatly) for validating old dates. This is more nearly complete && correct than most straight shell implementations using regex are likely to be. I deliberately excluded



Code:
/* chpdt.c 
usage chpdt filename 
      echo "$filname" | chpdt
*/
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#define isleapyr(y) (((y) % 4) == 0 && ((y) % 100) != 0 || ((y) % 400) == 0)
int leap[12]= {31,29,31,30,31,30,31,31,30,31,30,31};
int nleap[12]={31,28,31,30,31,30,31,31,30,31,30,31};


char  *date_ok(char *result, char *src)
{
	int value=atoi(src);
	int month=0;
	char *p=src;
	int *v=nleap;

    if( value >= 1900 && value < 2038 && (p=strchr(p, '-')) != NULL )
    {
        if(isleapyr(value))        
        	v=leap;
		value=atoi(++p);
		if(value >= 1 && value < 13 && (p=strchr(p, '-')) != NULL)
		{
			month=value;
			value=atoi(++p);
			if( value > 0 && value < v[ month - 1 ] )
				if( (p=strchr(p, '-')) != NULL)
					result=++p;
		}
    }
    return result;
}

char  *name_ok(char *p, char *src)
{
	if(src[4]=='-' && src[7]=='-' && src[10]=='-')
		p=date_ok(p, src);
	return p;
}

int main(int argc, char **argv)
{
	int retval=0;
	char tmp[PATH_MAX + 2]={0x0};
	char *p=NULL;
	if (argc < 2)
	{
		if(fgets(tmp, sizeof(tmp), stdin) ==NULL)
		{
			perror("I/O error");
			retval=1;
		};
		p=strchr(tmp, '\n');
		if(p!=NULL)
			*p=0x0;
	}
	else
		(void)strncpy(tmp, argv[1], PATH_MAX);
	p=tmp;
	if(strlen(tmp) > 10 && !retval) /* will return zero length if string is "date-"*/
		p=name_ok(p, tmp);
    if( fprintf(stdout, "%s", p) < 0)
    {
    	perror("I/O error");
    	retval=1;	
    }
    return retval;
}

Good luck with this.