Shell Scripting – How to Use grep on a Variable

grepshellstring

Let's say I have a variable

line="This is where we select from a table."

now I want to grep how many times does select occur in the sentence.

grep -ci "select" $line

I tried that, but it did not work. I also tried

grep -ci "select" "$line"

It still doesn't work. I get the following error.

grep: This is where we select from a table.: No such file or directory

Best Answer

Have grep read on its standard input. There you go, using a pipe...

$ echo "$line" | grep select

... or a here string...

$ grep select <<< "$line"

Also, you might want to replace spaces by newlines before grepping :

$ echo "$line" | tr ' ' '\n' | grep select

... or you could ask grep to print the match only:

$ echo "$line" | grep -o select

This will allow you to get rid of the rest of the line when there's a match.

Edit: Oops, read a little too fast, thanks Marco. In order to count the occurences, just pipe any of these to wc(1) ;)

Another edit made after lzkata's comment, quoting $line when using echo.

Related Question