1835036 Members
3901 Online
110073 Solutions
New Discussion

Re: using grep in script

 
Dave Chamberlin
Trusted Contributor

using grep in script

In the Posix or Bourne shell, I wish to extract lines from a file with strings like "Jul 15". On the command line I can do:
cat myfile | grep "Jul 15"
and this works. When I try this in a script like:
cat myfile | grep "Jul 18"
it works, but when I try to use a variable I can't get the script to work:

set ""Jul 15""
echo $1
cat myfile | grep $1

even though the echo gives "Jul 15" . Also the script:
cat myfile | grep $1
will not work for "Jul 15" as the input argument. I cannot get a script to work with any command line argument that has more than a single string. Does someone know how to do this?
4 REPLIES 4
Rick Garland
Honored Contributor

Re: using grep in script

In your script try the following:

DATE=`date %'+b +d'`
grep $DATE

I am assuming that you are wanting something to look for dates. This is for the current date.
RikTytgat
Honored Contributor

Re: using grep in script

Hi,

Rick is right. The catch is in the difference between single and double quotes. This is sometimes confusing when writing shell scripts.

Bye,
Rik
RikTytgat
Honored Contributor

Re: using grep in script

Hi,

Supplement:

When you like to pass a command line argument that contains whitespace as a single positional argument, enclose it in quotes.

Like:
myscript "This is a test"

$1 will contain the string "This is a test" (without the quotes).

If you want to use it as an argument to yet another command which should consider it as 1 positional argument, you should do

grep "$1"

Bye again,
Rik
Dave Chamberlin
Trusted Contributor

Re: using grep in script

It works fine if grep "$1" used instead of grep $1. Thanks for the help.