7

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.

12

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.

  • This solved it for me. I didn't know abot that sed function. Thank you! – mormaii2 Nov 14 '14 at 17:49
10

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
  • in this example, we want to delete lines 1 and 4, so NR%3==1 – glenn jackman Nov 14 '14 at 17:41
  • 4
    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) – Stéphane Chazelas Nov 14 '14 at 17:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.