30

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?

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Craig
  • 359
  • 1
  • 5
  • 9

4 Answers4

42
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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • 1
    Nice. The above case statement should be valid in the original `sh` too. – Alok Singhal Jan 21 '10 at 02:55
  • @ghostdog74 Best example of how to grep a string (rather than file) that I've found online. Thanks – james Jan 10 '13 at 18:19
  • Better call external commands, you get less dependent on the shell. – fiatjaf Jun 24 '16 at 17:46
  • This doesn't work on Solaris 9 for me. But this works: `echo "$long_str" | grep ``cat -`` "$shrt_str"` (I am sorry for the double backtics, haven't managed to escape them in any other way). – saulius2 Apr 30 '20 at 12:58
24

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
  • 776,304
  • 153
  • 1,341
  • 1,358
9

You want

if echo $long_str | grep -q $shrt_str; then
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
9

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
  • 346,391
  • 90
  • 374
  • 439