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... |
Try:
Code:
[ "`grep -c STRING FILE`" -gt "0" ] && command to execute |
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 |
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 |
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... |
&& 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 I hope that's cleared things up a bit. |
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. |