Search code examples
bashsedtail

How to extract x lines every y number of lines


I have a big file from which I want to extract x lines every y number of lines. I searched around and found some answers on how to print the first z lines, something like tail -n +<lines to skip + 1> I'm trying to combine it with sed but don't know how.


Solution

  • To print the first two lines of every tex lines, try:

    awk -v x=2 -v y=10 '(NR - 1) % y < x'
    

    For example:

    $ seq 20 | awk -v x=2 -v y=10 '(NR - 1) % y < x'
    1
    2
    11
    12
    

    How it works

    Awk reads through the input line-by-line. It will print the line if the condition (NR - 1) % y < x is true. NR is the line number starting at one for the first line.