4

Simply said, I just can't find a way to match a variable against some pattern containing spaces.

Here is what I expected to work (echo 'ok' string)

item='foobar baz'
pat=".+bar baz"
if [[ "$item" =~ "$pat" ]] ; then
    echo ok
fi

Adding/removing quotes around $pat does not seem to make any difference. I get those two erros below:

bash: conditional binary operator expected
bash: syntax error near `~='

Could someone please help me pointing out what I am doing wrong here ? Should I put the pattern right away (without any quotes/double quotes, nor variable reference) ? If that is the case, then how can I put spaces in ? (using reg-exp matching, not an alternative)

Thank you !

0

1 Answer 1

4

The syntax error is self-explanatory i.e. you have used ~= instead of =~.

Regarding the Regex pattern, just use $pat (and also $item), being a shell builtin [[ can handle word splitting:

item='foobar baz'
pat=".+bar baz"
if [[ $item =~ $pat ]]; then
    echo ok
fi

When you use double quotes around $pat i.e. "$pat", the Regex tokens . and + are treated literally.

Example:

$ item='foobar baz'; pat=".+bar baz"; if [[ $item =~ $pat ]]; then echo OK; fi
OK
8
  • pat="^.+bar baz$"
    – Costas
    Commented Dec 24, 2015 at 18:13
  • @Stphane check edits
    – heemayl
    Commented Dec 24, 2015 at 18:24
  • @heemayl Thank you for your time / code review .. No error anymore ! But I don't get the ok :p
    – Stphane
    Commented Dec 24, 2015 at 18:25
  • @Stphane yes..check edits..which version of bash you have?
    – heemayl
    Commented Dec 24, 2015 at 18:28
  • @heemayl GNU bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu)
    – Stphane
    Commented Dec 24, 2015 at 18:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .