1753862 Members
7430 Online
108809 Solutions
New Discussion юеВ

grep issues

 
SOLVED
Go to solution
Andres_13
Respected Contributor

grep issues

Hi,

I'm having issues with the following grep statement:

#!/bin/sh
File1="/tmp/Myfile"
String="100% packet loss"
Control="/tmp/Control_file.txt"

/usr/bin/grep $String $File1 > $Control
Check=`/sbin/cat $Control | /usr/bin/wc -l`
.
.
.

With this I'm getting
grep: can't open packet
grep: can't open loss

When I run it directly from command line:

# String='100% packet loss'
# /usr/bin/grep $String $File1 > $Control
grep: can't open packet
grep: can't open loss

But if I do:

# /usr/bin/grep '100% packet loss' $File1 > $Control
#

... It works! So what I'm doing wrong?

Regards!
5 REPLIES 5
Tim Nelson
Honored Contributor

Re: grep issues

there are spaces in your variable Strings.


change to
String=\"100% packet loss\"
Andres_13
Respected Contributor

Re: grep issues

Thanks Tim,

This what I'm get:

# String=\"100% packet loss\"
sh: packet: not found.
#

Patrick Wallek
Honored Contributor
Solution

Re: grep issues

Try this:

/usr/bin/grep "${String}" $File1 > $Control
James R. Ferguson
Acclaimed Contributor

Re: grep issues

Hi:

As Patrick suggested, quote the '$String' variable. This prevents the shell from evaluating it before 'grep' does.

When you did:

# String="100% packet loss"

# /usr/bin/grep $String $File1 > $Control

...The shell expanded things to:

# /usr/bin/grep 100% packet loss /tmp/Myfile > /tmp/Control_file.txt

...which isn't a syntax that 'grep' understands :-)

Regards!

...JRF...
Andres_13
Respected Contributor

Re: grep issues

It worked just fine.

Thanks for the explanation James!.

Quoting did the trick.

Regards!