Ed Flanagan
Ed Flanagan

Reputation: 13

Perl Regex not working in Bash script?

I have a regular expression:

^(.+?)(\.[^.]+$|$)

which separates a file name and the file extension (if there is one) http://movingtofreedom.org/2008/04/01/regex-match-filename-base-and-extension/

Works perfectly fine in Perl

Say $FILE ='.myfile.form.txt'

$1 is '.myfile.form' and

$2 is '.txt', as they should be

I know Bash regex and Perl regex aren't the same, but I've never had a problem with Bash Rematching until now

But when I try to use in in a Bash script as, say...

FILE='.myfile.form.txt'
[[ $FILE =~ ^(.+?)(\.[^.]+$|$) ]]

${BASH_REMATCH[1]} will just have the entire file name (.myfile.form.txt), and nothing in ${BASH_REMATCH[2]}

I'm wondering what's wrong/going on here

Thanks for any help!

Upvotes: 1

Views: 478

Answers (1)

ikegami
ikegami

Reputation: 385847

regex(7) which is referenced by regex(3) which is referenced by bash(1) makes no mention of greediness modifiers. Your pattern cannot be implemented in bash regex.

This doesn't mean you can't achieve what you want, though.

[[ $FILE =~ ^(.+)(\.[^.]*)$ ]] || [[ $FILE =~ ^(.*)()$ ]]
file="${BASH_REMATCH[1]}"
ext="${BASH_REMATCH[2]}"

Or something more straightforward like

if [[ $FILE =~ ^(.+)(\.[^.]*)$ ]]; then
   file="${BASH_REMATCH[1]}"
   ext="${BASH_REMATCH[2]}"
else
   file="$FILE"
   ext=""
fi

Upvotes: 1

Related Questions