Does bash support word boundary regular expressions?

前端 未结 8 1646
面向向阳花
面向向阳花 2020-12-01 05:30

I am trying to match on the presence of a word in a list before adding that word again (to avoid duplicates). I am using bash 4.2.24 and am trying the below:



        
8条回答
  •  佛祖请我去吃肉
    2020-12-01 05:54

    Yes, all the listed regex extensions are supported but you'll have better luck putting the pattern in a variable before using it. Try this:

    re=\\bmyword\\b
    [[ $foo =~ $re ]]
    

    Digging around I found this question, whose answers seems to explain why the behaviour changes when the regex is written inline as in your example.

    Editor's note: The linked question does not explain the OP's problem; it merely explains how starting with Bash version 3.2 regexes (or at least the special regex chars.) must by default be unquoted to be treated as such - which is exactly what the OP attempted.
    However, the workarounds in this answer are effective.

    You'll probably have to rewrite your tests so as to use a temporary variable for your regexes, or use the 3.1 compatibility mode:

    shopt -s compat31
    

提交回复
热议问题