1

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!

3
  • 6
    What makes you think bash and Perl accept the same regular expressions? They are different programs with different rules. Commented Jan 30, 2014 at 2:08
  • 1
    In a bash script if you want to match, you could use grep, with -P, for using Perl expressions. (more info: $grep --help ) Commented Jan 30, 2014 at 2:37
  • O sorry, I didn't clarify. I know they're not the same, I'm wondering what I could change so it will work as intended in a Bash script. And I did try 'grep -oP', but the system I need this to run on doesn't allow the -P flag, installed grep without it. Plus the rematching in grep won't save the group matching. And even with -o, a file name will be printed as one line, not separated Commented Jan 30, 2014 at 2:40

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.