Print every n lines from a file

后端 未结 4 897
醉话见心
醉话见心 2021-01-21 05:10

I\'m trying to print every nth line from file, but n is not a constant but a variable.

For instance, I want to replace sed -n \'1~5p\'

4条回答
  •  灰色年华
    2021-01-21 05:39

    awk can also do it in a more elegant way:

    awk -v n=YOUR_NUM 'NR%n==1' file
    

    With -v n=YOUR_NUM you indicate the number. Then, NR%n==1 evaluates to true just when the line number is on a form of 7n+1, so it prints the line.

    Note how good it is to use awk for this: if you want the lines on the form of 7n+k, you just need to do: awk -v n=7 'NR%n==k' file.

    Example

    Let's print every 7 lines:

    $ seq 50 | awk -v n=7 'NR%n==1'
    1
    8
    15
    22
    29
    36
    43
    50
    

    Or in sed:

    $ n=7
    $ seq 50 | sed -n "1~$n p" # quote the expression, so that "$n" is expanded
    1
    8
    15
    22
    29
    36
    43
    50
    

提交回复
热议问题