2

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
  • 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
    Commented Jan 22, 2016 at 17:37

2 Answers 2

1

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.

3
  • 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
    Commented Jan 22, 2016 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
    Commented Jan 22, 2016 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
    Commented Jan 22, 2016 at 18:00
0

Note that in tail -fn20, the 20 only comes into play at the very start.

tail will show you the first 20 lines, and then carry on displaying all new lines being added as they come (whether they come in batch of 1, 20 or 1000 lines).

Or in other words, tail -fn20 is like tail -n20 followed by tail -fn+1.

Here, you could do:

{ grep pattern | tail -n 20; tail -fn+1 | grep pattern; } < file

That is, do the first step by hand, and then have tail -f display all the rest.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .