Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 27 Jun 2012 11:11:12 -0500
From:      Tim Daneliuk <tundra@tundraware.com>
To:        freebsd-questions@freebsd.org
Cc:        Aleksandr Miroslav <alexmiroslav@gmail.com>
Subject:   Re: shell scripting: grepping multiple patterns, logically ANDed
Message-ID:  <4FEB30A0.4020306@tundraware.com>
In-Reply-To: <4FEB27DA.1090308@tundraware.com>
References:  <CACcSE1zwRcU_VQ16A2wiG4yWk4RBRykTXBono3xspw97zhDs7w@mail.gmail.com> <4FEB25E8.6000701@tundraware.com> <4FEB27DA.1090308@tundraware.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On 06/27/2012 10:33 AM, Tim Daneliuk wrote:
> On 06/27/2012 10:25 AM, Tim Daneliuk wrote:
>> On 06/27/2012 09:25 AM, Aleksandr Miroslav wrote:
>>> hello,
>>>
>>> I'm not sure if this is the right forum for this question, but here
>>> goes.
>>>
>>> I have the following in a shell script:
>>>
>>>
>>>      #!/bin/sh
>>>
>>>      if [ "$#" -eq "0" ]; then
>>>              find /foo
>>>      fi
>>>      if [ "$#" -eq "1" ]; then
>>>              find /foo | grep -i $1
>>>      fi
>>>      if [ "$#" -eq "2" ]; then
>>>              find /foo | grep -i $1 | grep -i $2
>>>      fi
>>>      if [ "$#" -eq "3" ]; then
>>>              find /foo | grep -i $1 | grep -i $2 | grep -i $3
>>>      fi
>>>
>>> Is there an easier/shorter way to do this? If there are 15 arguments
>>> supplied on the command line, I don't necessarily want to build 15 if
>>> statements.
>>>
>>> Thanks in advance for your answers.
>>
>> The following solution relies on the fact that you can include multiple
>> patterns for grep to match with the '-e' argument:
>>
>>
>>    #!/bin/sh
>>
>>    PATTERNS=`echo " $*" | sed s/\ /\ -e\ /g`
>>
>>    find /foo | grep $PATTERNS
>>
>> Notice that when constructing the $PATTERNS string out of the command line
>> args, you have to quote them with a prepended space character.  That's because
>> the subsequent 'sed' substitution needs to find a space *before* each argument
>> which it then replaces with "-e ".
>>
>
> Whoops, I just realized that I ORed them and you want them ANDed.  Hmmm ... must
> go think on that...


OK, here is an ANDing version:

  #!/bin/sh

   PATMATCH=`echo " $*" | sed s/' '/' | grep '/g`
   eval "find ./ $PATMATCH"


-- 
-----------------------------------------------------------------------
Tim Daneliuk





Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?4FEB30A0.4020306>