[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 335
  • Last Modified:

bash scripting - search a match in a string

I have a string on a variable, I want to search for two matches.. something like this:

var="Take the red pill, or the blue pill"

if [ "red pill" isin $var ]; <-- this I don't know
then
    echo "Somebody mentioned the red pill"
else
    echo "Somebody said something but not about the red pill"
fi

I googled for "search string" and stuff but I get awk and expr funtions that I don't seem to understand (or indeed it isn't me and the result of my search aren't right). Maybe I'm looking wrong. :S

Thaaanks experts :)
0
mmartha
Asked:
mmartha
2 Solutions
 
blklineCommented:
Someone with better regexp skills will undoubtedly jump in here but here's a quicky:

if echo $var | egrep -e '(^| )red( |$)'; then
   echo "Somebody mentioned the red pill"
else
   echo "Somebody said something but not about the red pill"
fi

We're looking for:

beginning of the line or a space, followed by the letters r e d followed by either a space or end-of-line.

Of course, punctuation will cause a problem after the word red in this example, so you could allow alter the regex slightly to allow non-character trailers after r e d:

'(^| )red([^:alpha:]| |$)'

Is this what you were looking for?
0
 
TintinCommented:
if echo "$var" | grep -qw "red pill'
then
    echo "Somebody mentioned the red pill"
else
   echo "Somebody said something but not about the red pill"
fi

The -w flag says to search for whole words and the -q flag is for quiet (ie. no output)
0
 
mmarthaAuthor Commented:
thank you both. :)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now