0

i can do tail -f -n20 <file> to see the last 20 lines of the file, live.

If i want to grep something, tail -f <file> | grep <pattern>, it will still be live, but will only grep through the output of tail, meaning I am not gaurunteed 20 lines of output at first. (if only 5 of 20 lines match my pattern, I only get 5 lines out of output)

If I do something like

grep <pattern> <file> | tail -n20 

I am gaurunteed 20 lines of output but it isn't live, nor is

cat <file> | grep <pattern> | tail -n20

How can I see a live update of the last n lines of a file after grepping?

  • 1
    @HaukeLaging that is incorrect. piping tail to grep will only grep out the last n lines output by tail. Imagine a file where the first 20 lines are the word "foo", the next 20 lines are the word "bar", then the next 5 lines are the word "foo". tail -f <file> yields 5 lines of bar, then 5 lines of foo, and thus tail -f <file> | grep foo gives 5 lines of foo. grep foo <file> yields 25 lines of foo, and so grep foo <file> | tail -n20 gives 20 lines of foo, so they are not the same – chiliNUT Jan 22 '16 at 17:37
0

You can use tee with process substitution >():

tail -f -n 20 file.log | tee >(grep 'pattern')

This will show you the last 20 lines of file.log and then the result of grep.

  • this isn't working, tail -f -n 20 file.log | tee yields the same output as tail -f -n 20 file.log | tee >(grep 'pattern') – chiliNUT Jan 22 '16 at 17:42
  • Which Distro and which shell are you on? Also check whether there is actually any output of the grep pattern you have given? – heemayl Jan 22 '16 at 17:51
  • I have confirmed grep gives me output. I am using the example file described in my comment above, and grepping for foo. Using: Centos 6.7 w/ bash 4.1.2 – chiliNUT Jan 22 '16 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.