views:

227

answers:

4

How would I do a regex match as shown below but with quotes around the ("^This") as in the real world "This" will be a string that can have spaces in it.

#!/bin/bash

text="This is just a test string"
if [[ "$text" =~ ^This ]]; then
 echo "matched"

else
 echo "not matched"
fi

I want to do something like

    if [[ "$text" =~ "^This is" ]]; then

but this doesn't match.

A: 

Have you tried:

^[\s]*This
Crimson
+2  A: 

You can use \ before spaces.

#!/bin/bash

text="This is just a test string"
if [[ "$text" =~ ^This\ is\ just ]]; then
  echo "matched"
else
  echo "not matched"
fi
too much php
+1 This is definitely the way to do it. Bash regexes used with `=~` should most often (always?) be unquoted.
Dennis Williamson
That's good to hear. I've never used bash regexes before, I just experimented and found that \ worked. *On S.O., it's correct until proven wrong!*
too much php
FWIW, this changed between Bash 3.1 and Bash 3.2. Bash 4.0 has a configurable `shopt -s/-u compat31` to toggle between the behaviors.
ephemient
A: 

can you make your problem description clearer?

text="This is just a test string"
case "$text" in
    "This is"*) echo "match";;
esac

the above assume you want to match "This is" at exactly start of line.

ghostdog74
+1  A: 

I did not manage to inline the expression like this:

if [[ "$text" =~ "^ *This " ]]; then

but if you put the expression in a variable you could use normal regex syntax like this:

pat="^ *This "
if [[ $text =~ $pat ]]; then

Note that the quoting on $text and $pat is unnessesary.

Edit: A convinient oneliner during the development:

pat="^ *This is "; [[ "   This is just a test string" =~ $pat ]]; echo $?
UlfR
The are no spaces at the beginning of `$text` so `$pat` should be `"^This"`. Also, quoting the variables here is not only unnecessary, it won't work. +1 for showing the variable format.
Dennis Williamson