Search code examples
linuxgreptailhead

grep tail and head wrong result


I want to show the 3 first lines and the 2 last lines that contain a word. I tried a grep command but it's not showing what I want.

grep -w it /usr/include/stdio.h | head -3 | tail -2

It only display the 2nd and 3nd lines that contain "it" in it.


Solution

  • The issue here is that tail never receives the output of grep, but rather only the first 3 lines of the file. To make this work reliably you either need to grep twice, once with head and once with tail or multiplex the stream, e.g.:

    grep -w it /usr/include/stdio.h |
    tee >(head -n3 > head-of-file) >(tail -n2 > tail-of-file) > /dev/null
    cat head-of-file tail-of-file
    

    Output here:

       The GNU C Library is free software; you can redistribute it and/or
       modify it under the terms of the GNU Lesser General Public
       The GNU C Library is distributed in the hope that it will be useful,
       or due to the implementation it is a cancellation point and
    /* Try to acquire ownership of STREAM but do not block if it is not