Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I grep complex strings in variables?

I am trying to grep for a small string in a much larger string. Both strings are being stored as variables and here is a code example:

#!/bin/bash  long_str=$(man man) shrt_str="guide"  if grep -q $shrt_str $long_str ; then         echo "Found it!" fi 

I don't think variable expansion is working the way I expect it to. I have tried [ ] and [[ ]], also quoting the variables and piping the output to /dev/null but no matter what I do it won't work.

Does anyone have any ideas?

like image 891
Craig Avatar asked Jan 21 '10 02:01

Craig


2 Answers

if echo "$long_str" | grep -q "$shrt_str";then   echo "found" fi 

or

echo "$long_str" | grep  -q  "$shrt_str"  && echo "found" || echo "not found" 

But since you are using bash shell, then use shell internals. No need to call external commands

shrt_str="guide" case "$long_str" in     *"$shrt_str"* ) echo "Found";;    * ) echo "Not found";; esac 
like image 66
ghostdog74 Avatar answered Oct 02 '22 13:10

ghostdog74


grep is for files or stdin. If you want to use a variable as stdin then you need to use bash's herestring notation:

if grep -q "$shrt_str" <<< "$long_str" ; then 
like image 44
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 13:10

Ignacio Vazquez-Abrams