Search code examples
linuxtail

Linux tail command includes more lines than intended


so I want to get a little into Linux scripting and started by a simple example in a book. In this book, the author wants me to grab the five lines before "Step #6: Configure output plugins" from snort.conf.

Analogous to the author I determined where the line is that I want, which returns 445 for me. If I then use tail the result returns more text than I expect and the searched line that should be in line 5 is at line 88. I fail to understand how I use the tail command and start at the specific line but then more text is included.

To search for the line I used

nl /etc/snort/snort.conf | grep output.

To get the 5 lines before including the searched line:

tail -n+440 /etc/snort/snort.conf | head -n+6 

where as the tail statement seems to be the problem. Any help is appreciated on why my answer is not working!


Solution

  • Your tail command is correct in principle.

    The problem lies in the way in which you acquire the line number using nl. The nl command does not count empty lines by default, while the tail command does. You should specify in your nl command that you want to count the empty lines as well, which you can do using the -b, (body-numbering) option and specify a as your style. This would look as follows:

    nl -ba /etc/snort/snort.conf | grep output.
    

    From nl --help:

    Usage: nl [OPTION]... [FILE]...
    Write each FILE to standard output, with line numbers added.
    
    With no FILE, or when FILE is -, read standard input.
    
    Mandatory arguments to long options are mandatory for short options too.
      -b, --body-numbering=STYLE      use STYLE for numbering body lines
    
    [...]
    
    By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn.  CC are
    two delimiter characters for separating logical pages, a missing
    second character implies :.  Type \\ for \.  STYLE is one of:
    
      a         number all lines
      t         number only nonempty lines
    

    Number all lines and use that line number in tail.