0

I am trying to do a regular expression match with a variable that contains an asterisk.

The following set of commands in Bash does filename expansion with the asterisk in the variable on the left-hand side of the operator.

test='part1 * part2'
[[ "$test" =~ ^(.+)\ .\ (.+)$ ]] && echo $BASH_REMATCH

Results in: part1 FILE1 FILE2 part2

But it should result in: part1 * part2

I have searched and searched but cannot figure out why this is happening.

1 Answers1

1

I realized while asking, the regular expression matching is working fine. There is no expansion happening inside the double brackets. The expansion is occurring after the match, when the result is echoed. The $BASH_REMATCH variable contains an asterisk, and needs to be double-quoted.

The correct set of commands is:

test='part1 * part2'
regex='^(.+) . (.+)$'
[[ "$test" =~ $regex ]] && echo "$BASH_REMATCH"

UPDATE: Set regular expression outside of test.

  • Quite right. (As a rule, you should *always* quote expansions unless given an explicit reason to do otherwise). – Charles Duffy Oct 11 '17 at 17:05
  • 1
    It's also good practice to declare the regex outside of the test because it's a) easier to read (no escaping necessary) and b) works for all Bash versions (see [here](http://mywiki.wooledge.org/BashGuide/Patterns) under "Regular Expressions"). – Benjamin W. Oct 11 '17 at 17:12
  • 1
    Thanks @BenjaminW., I updated the answer. – Owen T. Heisler Oct 12 '17 at 18:12