LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Execute command when line matches (https://www.linuxquestions.org/questions/programming-9/execute-command-when-line-matches-4175417405/)

pgb205 07-18-2012 10:56 AM

Execute command when line matches
 
I'm monitoring a file with tail -f

tail -f <filename> |grep <string>

what i want to do is to execute another script when grep finds a new match.

Is there an event message that can be captured or some other method?

pixellany 07-18-2012 11:05 AM

Code:

if grep <string> filename 1>/dev/null; then
    <do stuff>
fi


chrism01 07-18-2012 08:44 PM

Unfortunately, this seems to be an ever growing log file, so I don't think that would work because you'd have to know where you got to last time, then loop round and continue from that line num (not to mention logrotate issues).
I'd use http://search.cpan.org/~mgrabnar/Fil...0.99.3/Tail.pm instead, which is designed especially for this situation.

dru8274 07-18-2012 11:45 PM

Perhaps something like this...
Code:

while IFS= read var ; do

    # Some script here to parse the line stored in $var

done < <(tail -f tailfile | grep 'some pattern here')


Kenhelm 07-19-2012 02:29 AM

This is working on my system using GNU grep.
Code:

tail -f <filename> | grep --line-buffered <string> | while read;do
                                                      <scriptname>
                                                    done

Without the '--line-buffered' option the matched lines would be held back in a buffer instead of being sent immediately through the pipe to the while loop.

David the H. 07-20-2012 11:38 AM

Or you could eliminate grep entirely.

Code:

while read -r; do

        [[ $REPLY == *string* ]] && ./scriptname

done < <( tail -f file )



All times are GMT -5. The time now is 11:10 AM.