How to check file name format using shell script?

Hi,

I am writting a script, which accepts input file as parameter.
Input file name is aa_bb_cc_dd_ee.<ext>
I need to check that input file name should be of 5 fileds.
Please help me out. :confused:

I can think of a quick way to do this via 'cut'.
The first part would be to get rid of the file extension:

FILE_SHORT_NAME=`echo $FILE_NAME | cut -d'.' -f1`

The next would be to split the remaining name into 5 parts and check if each part is present:

PART_1=`echo $FILE_SHORT_NAME | cut -d'_' -f1`
PART_2=`echo $FILE_SHORT_NAME | cut -d'_' -f2`
PART_3=`echo $FILE_SHORT_NAME | cut -d'_' -f3`
PART_4=`echo $FILE_SHORT_NAME | cut -d'_' -f4`
PART_5=`echo $FILE_SHORT_NAME | cut -d'_' -f5`

You could then do basic checks to make sure that none of these parts is an empty string:

if [ -z $PART_1 ]
then
        echo "Please enter a correct filename"
fi

And similarly for the other parts as well. Up to you whether you want to get them in bulk and check them or get them one by one and check them and throw an error at the first place itself!

case could be even more useful.

assuming your pattern is ;

<any_lowercase_alphabet>_<any_lowercase_alphabet>_<any_lowercase_alphabet>_<any_lowercase_alphabet>_<any_lowercase_alphabet>.ext 

try something like:

case $file in
 
[a-z]*_[a-z]*_[a-z]*_[a-z]*_[a-z].ext ) echo yes ;;
* ) echo no;;
 
esac

Once I get file name excluding extension, I just want to count number of fields insted of each field value check.
for example,
if my file name is "aa_bb_cc_dd_ee.<ext>"
using below,

FILE_SHORT_NAME=`echo $FILE_NAME | cut -d'.' -f1`

now i receive only file name as "aa_bb_cc_dd_ee"
Now I need to count number of fields seperated by "_"underscore.
Please help me out.

n=$(echo $FILE_NAME |awk -F _ '{print NF}' )

if [ "$n" -ne 5 ] 
then
        echo "Please enter a correct filename aa_bb_cc_dd_ee.<ext>"
        exit
fi

I need code in korn shell script and not in awk with bash.

I had mentioned this earlier in my post. To get the individual parts via cut, do the following:

PART_1=`echo $FILE_SHORT_NAME | cut -d'_' -f1`
PART_2=`echo $FILE_SHORT_NAME | cut -d'_' -f2`
PART_3=`echo $FILE_SHORT_NAME | cut -d'_' -f3`
PART_4=`echo $FILE_SHORT_NAME | cut -d'_' -f4`
PART_5=`echo $FILE_SHORT_NAME | cut -d'_' -f5`

This really smells like homework.

Thread closed!