How to 'grep' a continuous stream?

前端 未结 12 1393
清酒与你
清酒与你 2020-11-22 11:15

Is that possible to use grep on a continuous stream?

What I mean is sort of a tail -f command, but with grep on t

相关标签:
12条回答
  • 2020-11-22 11:34

    If you want to find matches in the entire file (not just the tail), and you want it to sit and wait for any new matches, this works nicely:

    tail -c +0 -f <file> | grep --line-buffered <pattern>
    

    The -c +0 flag says that the output should start 0 bytes (-c) from the beginning (+) of the file.

    0 讨论(0)
  • 2020-11-22 11:35

    you may consider this answer as enhancement .. usually I am using

    tail -F <fileName> | grep --line-buffered  <pattern> -A 3 -B 5
    

    -F is better in case of file rotate (-f will not work properly if file rotated)

    -A and -B is useful to get lines just before and after the pattern occurrence .. these blocks will appeared between dashed line separators

    But For me I prefer doing the following

    tail -F <file> | less
    

    this is very useful if you want to search inside streamed logs. I mean go back and forward and look deeply

    0 讨论(0)
  • 2020-11-22 11:37

    I use the tail -f <file> | grep <pattern> all the time.

    It will wait till grep flushes, not till it finishes (I'm using Ubuntu).

    0 讨论(0)
  • 2020-11-22 11:37

    Didn't see anyone offer my usual go-to for this:

    less +F <file>
    ctrl + c
    /<search term>
    <enter>
    shift + f
    

    I prefer this, because you can use ctrl + c to stop and navigate through the file whenever, and then just hit shift + f to return to the live, streaming search.

    0 讨论(0)
  • 2020-11-22 11:37

    Use awk(another great bash utility) instead of grep where you dont have the line buffered option! It will continuously stream your data from tail.

    this is how you use grep

    tail -f <file> | grep pattern
    

    This is how you would use awk

    tail -f <file> | awk '/pattern/{print $0}'
    
    0 讨论(0)
  • 2020-11-22 11:42

    This one command workes for me (Suse):

    mail-srv:/var/log # tail -f /var/log/mail.info |grep --line-buffered LOGIN  >> logins_to_mail
    

    collecting logins to mail service

    0 讨论(0)
提交回复
热议问题