jlp jlp - 7 months ago 19
Bash Question

How to check if a file name matches regex in shell script

I have a shell script that needs to check if a file name matches a certain regex, but it always shows "not match". Can anyone let me know what's wrong with my code?

fileNamePattern=abcd_????_def_*.txt
realFilePath=/data/file/abcd_12bd_def_ghijk.txt

if [[ $realFilePath =~ $fileNamePattern ]]
then
echo $realFilePath match $fileNamePattern
else
echo $realFilePath not match $fileNamePattern
fi

Answer

you should use RegEx's instead of wildcards:

{ ~ }  » fileNamePattern="abcd_...._def_.*\.txt"                                                                    ~
{ ~ }  » realFilePath=/data/file/abcd_12bd_def_ghijk.txt                                                            ~
{ ~ }  » if [[ $realFilePath =~ $fileNamePattern ]]                                                                 ~
\ then
\     echo $realFilePath match  $fileNamePattern
\ else
\     echo $realFilePath not match $fileNamePattern
\ fi

Output:

/data/file/abcd_12bd_def_ghijk.txt match abcd_...._def_.*\.txt