I'm not sure of exactly what your issue is.  I'm thinking you need the 
"--", so I made a script with that, exactly like this:


-------begin script on next line---------
#!/bin/bash

PATTERN=$1

grep -Eic -- "$PATTERN"
-------end script on previous line---------


And I ran it:


$ echo -e "-testa\n-testb\nblah\nfoo\nbar\ntest\na-test" | ./script -test
3


That's the right answer.  Note that if you don't have a filename, you have 
to grep from stdin, which is what I did.

Mike


On Fri, 6 Dec 2013, canito at dalan.us wrote:

> In the process of writing a script which I would like to count the number 
> matched patterns (command line parameters).
>
> The issue I am running into using grep is that the string has a dash in 
> front, and it throws an error.
>
> E.g:
>
> ./script -test
>
> PATTERN=$1
>
> egrep -ic $PATTERN --> egrep: invalid option -- 't'
>
> awk and egrep work using a file, but not on a variable:
>
> EXAMPLE=`awk '/test/ { nlines++ } {print nlines}' $PATTERN`
>
> awk: cmd. line:1: fatal: cannot open file `-test' for reading (No such file 
> or directory)
>
> I know using and if command works, so am I just over doing it? What am I 
> doing wrong?
>
> if [[ $PATTERN == "-test" ]; then
>
> Thanks in advanced!
>
> Saul David Alanis