Reputation: 315
I have the following code written to check if my filename ends with some format like given below. It is working when tested online at https://regex101.com/ but not in linux bash. Please help me find out the issue.
Ex:
timestamp_foramt="^[\s\S]+_INFT_[0-9]{8}_[0-9]{6}[.][\w]+$"
FNAME="Payments.test_INFT_20191218_075918.txt" #example
if [[ ! $FNAME =~ $timestamp_foramt ]]; then echo non-format; else echo format; fi
non-format
Please help me understand why it is not working in bash. Did I commit something wrong in regex for timestamp_foramt
?
Upvotes: 2
Views: 162
Reputation: 626690
You can fix the current expression like this:
timestamp_foramt="^.+_INFT_[0-9]{8}_[0-9]{6}\.[[:alnum:]_]+$"
FNAME="Payments.test_INFT_20191218_075918.txt" #example
if [[ ! $FNAME =~ $timestamp_foramt ]]; then
echo 'non-format';
else
echo 'format';
fi;
See the online Bash demo.
Main points:
[\s\S]
can be used in Perl and other NFA regex engines to match any character, in POSIX ERE, used in Bash, you may simply use a .
\w
is better written as [[:alnum:]_]
in POSIX ERE as it is more portable to match letters, digits and underscores.Upvotes: 3