1752801 Members
5591 Online
108789 Solutions
New Discussion юеВ

Help with grep and if

 
SOLVED
Go to solution
dictum9
Super Advisor

Help with grep and if

I need code like this:

if [[ grep string $file ]]
then
file contains string
else
file does not contain string

fi

I got this but it errors on "]]"

10 REPLIES 10
Wouter Jagers
Honored Contributor
Solution

Re: Help with grep and if

hi,

if [ `grep string $file | wc -l` -gt 0 ]
..

should work better.

Cheers

an engineer's aim in a discussion is not to persuade, but to clarify.
gstonian
Trusted Contributor

Re: Help with grep and if

try

FOUND=`grep string $file`
if [[ -n $FOUND ]]
then
contains value
else
contains nothing

-n is non zero check whereas -z is a zero check

Cheers
Peter Godron
Honored Contributor

Re: Help with grep and if

Hi,

a=`grep 09 $file`
if [ -n "$a" ]
then
echo file contains string
else
echo file does not contain string
fi
Heironimus
Honored Contributor

Re: Help with grep and if

If you don't actually need to keep the matching lines you can use grep's exit code.

if grep 'string' "$file" 1>/dev/null 2>&1 ; then
echo "$file contains string"
else
echo "$file doesn't contain string, please add some"
fi
dictum9
Super Advisor

Re: Help with grep and if

I actually got it to work by removing the [[ and ]]

James R. Ferguson
Acclaimed Contributor

Re: Help with grep and if

Hi:

The 'grep' filter will return zero (0) if there are matches; one (1) if not. Hence:

# grep local /etc/hosts > /dev/null || echo "no matches!"

...is a terse way to meet your goal.

You can also count and return the number of matches with the '-c' switch. See the manpages for more information.

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Help with grep and if

You can improve Heironimus' solution by using grep -q, to not produce any output.
Sandman!
Honored Contributor

Re: Help with grep and if

Unless there is a compelling reason to use the if statement, you could always use the following:

# grep string file && echo file contains string || echo file does not contain string

~cheers
Daavid Turnbull
Frequent Advisor

Re: Help with grep and if

I always just use the exit code from grep:

grep -q string $file
if [ $? -eq 0 ]
then
echo "string is in $file"
else
echo "string is not in $file"
fi

Your friends here are:

man test
man grep
Behold the turtle for he makes not progress unless he pokes his head out.