Delete every Nth line in shell

14,682

Solution 1

If you have GNU sed, you could use the n~m (n skip m) address notation

sed '1~3d' file

which deletes every third line, starting at the first.

Solution 2

To select only lines modulo N with awk try

awk '!(NR%2)' file

or

awk 'NR%3==0' file

Here NR denotes number of rows processed so far.


In your specific case (remove all lines with Y):

$ echo 'YYYYYY
XXXXXX
XXXXXX
YYYYYY
XXXXXX
XXXXXX' | awk '!(NR%3==1)'
XXXXXX
XXXXXX
XXXXXX
XXXXXX
Share:
14,682

Related videos on Youtube

mormaii2
Author by

mormaii2

Updated on September 18, 2022

Comments

  • mormaii2
    mormaii2 over 1 year

    I'm trying to delete a line after N lines using awk and I can't seem to get it right. The file format is like this

    YYYYYY
    XXXXXX
    XXXXXX
    YYYYYY
    XXXXXX
    XXXXXX
    

    The real example would be

    office3
    3
    1
    office3
    6
    1
    office3
    6
    3
    office3
    1
    1
    

    How can I delete the YY lines or the lines that say "office". I need to delete a line every two lines regardless of their content.

  • Angel Todorov
    Angel Todorov over 9 years
    in this example, we want to delete lines 1 and 4, so NR%3==1
  • mormaii2
    mormaii2 over 9 years
    This solved it for me. I didn't know abot that sed function. Thank you!
  • Stéphane Chazelas
    Stéphane Chazelas over 9 years
    This solution has the advantage of being standard and portable to all POSIX systems (even pre-POSIX ones as except for the first one, it works in the original awk from 1979)