-2

I am trying to use regex to match a filename out of a path.

#!/bin/bash
regex=[^/]+?(?=.zip)
path="/home/quid/Downloads/file.zip"

if [[ $path =~ $regex ]]
then
     echo "Found a match"
     echo $BASH_REMATCH
fi

I should get

Found a match
file

Instead bash gives me this error

another.sh: line 2: syntax error near unexpected token `('
another.sh: line 2: `reg=[^/]+?(?=.zip)'

If I put the regex in a quotes, it no longer is recognized as regex. I have zsh 5.8 and bash 5.0.16 and it doesn't work on both shells.

How can I get bash to recognize the regex or not give me an error for using regex groups?

7
  • (?=...) is not valid POSIX ERE syntax. Be sure you use the right regex language variant. Commented Apr 18, 2020 at 1:16
  • ERE doesn't allow non-greedy modifiers either. +? and *? don't mean anything here. Commented Apr 18, 2020 at 1:17
  • regex='([^/.]+)([.]zip)?$' may not be exactly what you want, but its validity does demonstrate that grouping is not the part of your original expression that's illegal. Commented Apr 18, 2020 at 1:20
  • BTW, you need to use quotes when assigning to the regex variable, and not use quotes when expanding that variable, to get consistent and reliable behavior. Commented Apr 18, 2020 at 1:23
  • Thank you for the help Charles. I have been testing on regexr which used the javascript ERE so that explains why it doesn't work with bash. Thanks for the extra tips. I'll be trying to just get "file" and not "file.zip" now. Commented Apr 18, 2020 at 1:25

1 Answer 1

-1
#!/bin/bash
regex='([^/.]+)([.]zip)?$'
path="/home/quid/Downloads/file.zip"

if [[ $path =~ $regex ]]
then
     echo "Found a match"
     echo "${BASH_REMATCH[1]}"
fi

Using Charles' regex and ${BASH_REMATCH[1]} gives me just the file name without the extension.

2
  • 1
    echo "${BASH_REMATCH[1]}" -- see BashPitfalls #14. Commented Apr 18, 2020 at 2:14
  • 2
    That said, usually I wouldn't use a regex for this at all. filename=${path##*/}; filename=${filename%.zip} will arrive at your original intent, using only parameter expansions. Commented Apr 18, 2020 at 2:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.