Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex match a string with spaces (use quotes?) in an if statement

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.

like image 948
Mint Avatar asked Oct 21 '09 06:10

Mint


1 Answers

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
like image 141
too much php Avatar answered Sep 22 '22 03:09

too much php