Does Filename Match Pattern

Hi,

I am writing a BASH script. I have a list of files and I would like to make sure that each is of a specific pattern (ie [AT]*.L2). If not I would like to remove that file. How do I test whether a filename matches a given pattern?
Thanks a lot.

Mike

Use the ls command and check its return code

ls -l [AT]*.L2  > /dev/null 2>&1 

Thank you for the reply! What does the "&1" indicate? Are you outputting the standard error of the ls statement?

Mike

shopt -s extglob
rm !([AT]*.L2)
case $filename in
     [AT]*.L2) printf "%s matches\n" "$filename" ;;
     *) printf "%s does not match\n" "$filename" ;;
esac 

The '&1' redirects the output of stderr to the output of stdout, which in this case is /dev/null. It could have been easily written as

ls -l [AT]*.L2  > /dev/null  2> /dev/null

The redirection of the output supresses any results or error messages. In this case you only care about the return code.

Hi cfajohnson,

Yes I was thinking about doing that. However, the pattern that I would like to match is condition dependent. I would like to do something like this:

if [ $START_LEVEL = 0 ]; then
        PATTERN_ARRAY=('[AT]*.L0_LAC' 'MOD00.[AP]*.PDS')
elif [ $START_LEVEL = 1 ]; then
        PATTERN_ARRAY=([AST]*.L1A_[GL]AC* S*.L1A_MLAC*)
elif [ $START_LEVEL = 2 ]; then
        PATTERN_ARRAY=([AST]*.L2_[GL]AC* S*.L2_MLAC*)
elif [ $START_LEVEL = 3 ]; then
        PATTERN_ARRAY=([AST]*_*_*.L3)
fi

for ENTRY in *; do
     for PATTERN in ${PATTERN_ARRAY[@]}; do
          case $ENTRY in
               $PATTERN)
               echo 'Entry matches pattern'
               ;;
               *)
               echo 'Entry does NOT match pattern'
               ;;
          esac
     done
done

However, the shell appears to be performing the pattern matching in if statements. Is there a way to get around that? Thank you.

Mike

The shell performs filename expansion anywhere you have an unquoted pattern. If you do not want it expanded, quote it.

You have unquoted patterns in your array assignments and in the array expansion.

Yes I thought that would work but the quoting doesn't seem to be working:

rrdhcp72-277:L0 msb65$ ls
A2008283115500.L0_LAC MOD00.P2008183.0240_1.PDS
A2008291124500.L0_LAC temp
A2008304121500.L0_LAC
rrdhcp72-277:L0 msb65$ pattern='A*'
rrdhcp72-277:L0 msb65$ echo $pattern
A2008283115500.L0_LAC A2008291124500.L0_LAC A2008304121500.L0_LAC

Why is the shell still expanding filename? I am using bash on OS 10.5

You haven't quoted the pattern.

echo "$pattern"

ahaa!!! thank you. One last question: what is the difference between '' and ""? Thanks for all your help. I really appreciate it.

Mike

Try it and see.