LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   use grep and execute a command if string is found (https://www.linuxquestions.org/questions/linux-general-1/use-grep-and-execute-a-command-if-string-is-found-347165/)

plisken 07-27-2005 12:05 AM

use grep and execute a command if string is found
 
I'm looking to search a file for a string and if that string is found at least once in the file then I'm looking to perform an action like so:

grep -q "some_string" my_file [if TRUE perform Command]
ie. if my_file contains some_string then perform the command and if not, do nothing.

I know you can do this sort of thing with find and -exec but hoq so with grep?

I'm sure there will be a VERY simply explination, so please go for it.

Thanks in advance...

Matir 07-27-2005 12:20 AM

Try:
Code:

[ "`grep -c STRING FILE`" -gt "0" ] && command to execute

APB_4 07-27-2005 05:58 AM

Hey Matir won't that execute the command whatever? How about something like this:

Code:

if grep -q "some_string" my_file; then perform COMMAND; fi

Matir 07-27-2005 08:35 AM

It will only perform the command if grep found one or more matches. Alternatively (deriving from yours) you could do:
Code:

grep -q string file && command

plisken 07-27-2005 01:36 PM

grep -q string file && command

Excellent, this is EXACTLY what I am looking for, knew it would be simple...

I also assume ir I run:

grep -q string file ; command

It will execute the command regardless of a TRUE condition.

I know & allows something to run in the backgroiund, but what exactly does the && mean?

Right now, thanks though...

Matir 07-27-2005 01:51 PM

&& means AND.
|| means OR.

How it works is this:
1) Bash sees the && and realizes "ah, I'm evaluating a conditional expression". It doesn't matter that we'll never do anything with the combined condition.
2) Bash executes the first part (before the &&) and makes a decision: if the first part returns non-zero (an error) it realizes "well, false and any value return false, so let's skip executing the second part". However, if it returns 'true' (0), bash knows it has to evaluate the output of the second part to determine the final condition.

In other words, suppose we have:
command1 && command2

Bash would see it like this:
Code:

if RESULT_OF_COMMAND1 == FALSE
    return FALSE
else
    if RESULT_OF_COMMAND2 == FALSE
        return FALSE
    else
        return TRUE
    endif
endif

(That's just pseudocode, btw, don't try to execute it) If COMMAND1 gives false, then it never tries to get a "result of command 2".

I hope that's cleared things up a bit.

archtoad6 07-28-2005 11:06 AM

Thanks for the reminder of grep's '-q' option -- I was about to put foot in mouth by suggesting you add >/dev/null.


All times are GMT -5. The time now is 09:25 AM.