Home > Blockchain >  How to grab every n,n 1 th lines from a text file
How to grab every n,n 1 th lines from a text file

Time:10-28

I have a huge text file where i need to grab every n, n 1 th line in a separate file.

I came across sed command but that could help me grab every n th line only from a text file. For example:

**

$ sed -n '0~4p' somefile**
**```**
Any suggestions on grabbing n 1th line at the same time?


**

$ sed -n '0~4p' somefile** ```

CodePudding user response:

Here's one possible solution (guessing that this is the required output):

$ seq 20 | sed -n '0~4{N;p}'
4
5
8
9
12
13
16
17

As per the manual for the N command:

Add a newline to the pattern space, then append the next line of input to the pattern space. If there is no more input then sed exits without processing any more commands. When -z is used, a zero byte (the ascii ‘NUL’ character) is added between the lines (instead of a new line).

If 20 should also be part of the output for the above input, you can use:

seq 20 | sed -n '0~4{p;n;p}'

# alternative solution if ~ address range isn't supported
seq 20 | sed -n '1b; n;n;p;n;p'

CodePudding user response:

The ~ option to sed is non-standard, but might be made to do what you want. But it seems more natural to use awk:

 awk 'NR>1 && NR % n  < 2' n=5

(eg):

$ yes | nl | sed 20q |  awk 'NR>1 && NR % n  < 2' n=5
     5  y
     6  y
    10  y
    11  y
    15  y
    16  y
    20  y

CodePudding user response:

This might work for you (GNU sed):

sed -n '4~4, 1p' file

This will print the 4th plus one lines starting at line 4.

  • Related