views:

40

answers:

4

All - I am trying to grep for a small string in a much larger string. Both strings are being stored as variables. This code is an 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. No matter what it won't work.

Ideas?

Thanks, C

+2  A: 

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
Ignacio Vazquez-Abrams
A: 

You want

if echo $long_str | grep -q $shrt_str; then
Alok
typo, extra 'if' ?
ghostdog74
@ghostdog: thanks, bad copy-paste error.
Alok
+1  A: 
echo "$long_str" | grep -q "$shrt_str"
if [ $? -eq 0 ];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
ghostdog74
Nice. The above case statement should be valid in the original `sh` too.
Alok
yes, it should work on bourne as well, if not mistaken.
ghostdog74
That is perfect. Thanks.
Craig
+1  A: 

Another Bash-specific technique:

if [[ $long =~ $short ]]    # regex match
then
    echo "yes"
fi

But if you don't need the long string in a variable:

if man man | grep $short; then ...

but I'm assuming that was just for the purpose of having an example.

Dennis Williamson
I tried the =~ solution but it didn't work. Nor does the test man page include the "~" as an operator.
Craig
`=~` is not a `test` operator, it's a Bash operator (note the double square brackets). It also works in ksh and zsh.
Dennis Williamson