Nexus
Nexus

Reputation: 71

Unix awk deleting every two lines

Basically I need to print 2 lines then delete two lines and so on.

awk 'BEGIN {count = 0} if(count == 4){count = 0} else if(count <= 1) {print,count++} else {count++}' f4

I am getting syntax errors.

or

awk '{count = 0; if(count == 4)count = 0; else if(count <= 1) print count++; else count++;}' f4

It prints all zeros.

I've also tried

awk 'NR%3 && NR%4' f4

Which is close but multiples of 3 and 4 are not printed.

Thanks

EDIT: GOT IT!

awk 'BEGIN{count = 0};{ if(count == 3)count = 0; else if(count <= 1) {print; count=count+1;} else count=count+1;}' f4

Upvotes: 1

Views: 2350

Answers (3)

Jotne
Jotne

Reputation: 41456

This should be one of the shortest and simplest to explain

awk 'NR%4==1 || NR%4==2'


NR%4==1 would print every forth line starting at one
NR%4==2 would print every forth line starting at two
|| this is an logical or

Given this file

cat file
one 1
two 2
three 3
four 4
five 5
six 6
seven 7
eight 8
nine 9
ten 10
eleven 11
twelve 12
thirteen 13
fourteen 14
fifteen 15
sixteen 16
seventeen 17
eighteen 18
nineteen 19
twenty 20


awk 'NR%4==1 || NR%4==2' file

Gives:

one 1
two 2
five 5
six 6
nine 9
ten 10
thirteen 13
fourteen 14
seventeen 17
eighteen 18

A variation using &&

awk 'NR%4 && NR%4!=3'

Upvotes: 8

user2719058
user2719058

Reputation: 2233

This works for me:

awk 'int((NR-1)/2)%2 == 0'

Upvotes: 2

Birei
Birei

Reputation: 36262

Use getline function to read following lines and discard those that you don't want to print:

awk '{ print; getline; print; getline; getline }' infile

Upvotes: 2

Related Questions