I'm tasked with writing a shell script which checks that a filename conforms to a specific pattern and I'm not sure how to go about it. The filename should follow a pattern which looks like: (Project-ID)_(Env)_(Source-System-ID)_(DataDescriptor)_(CCYYMMDD)_(Seq)_(Freeformat)_(codepage)Project_ID should be alphanumeric and between 3-8 characters.Env should consist of a 3 character code (DEV, SYT, SIT, UAT or PRD)Source-System-ID should be a variable numberDataDescriptor should be alphanumeric such as CUSTCCYYMMDD should be a date in the format CCYYMMDDSeq should be a number such as 01, 02, 03 etcFreeformat should be alphanumeric - used to give the filename additional descriptioncodepage should represent the file extension such as .ascii or .EBCDICAn example file might look like:ABC_PRD_00227_ACC_20130128_01_LTSB.CP1252If the file doesn't conform to the pattern it would be good if some sort of warning could be displayed.
How do I check that a filename conforms to a pattern?
shell script;grep;filenames;patterns
Assuming you use a recent version of zsh, ksh93 or bash and the filename doesn't contain newline characters:# split up the filename into its partsIFS=_ read -r pjid env srcid desc date seq free <<< $filename# extract the codepage from the free textcode=${free##*.}free=${free%.*}# validateif  [[ $pjid  =~ ^[[:alnum:]]{3,8}$ ]]                                  &&    [[ $env   == DEV || $env == SYT || ... ]]                       &&    [[ $srcid =~ ^[[:digit:]]+$ ]]                                      &&    [[ $desc  =~ ^[[:alnum:]]+$ ]]                                      &&    [[ $date  =~ ^[[:digit:]]{8}$ ]] && date -d $date >/dev/null 2>&1 &&    [[ $seq   =~ ^[[:digit:]]+$ ]]                                      &&    [[ $free  =~ ^[[:alnum:]]+$ ]]                                      &&    [[ $code  =~ ^[[:alnum:]]+$ ]]  # need specific codepage validation?then    echo file name format is OKfi