0

With fairly simply awk:

awk '(NR%3)' awk.write

for this file:

this line 1 no un1x
this lines 22 0
butbutbut this 33 22 has unix
but not 1
THIS is not
butbutbut ffff
second line

I have output as:

this line 1 no un1x
this lines 22 0
but not 1
THIS is not
second line

But the last line is not wanted since it doesn't qualify the definition of consecutive.

How can I the get the first two of every three consecutive lines?

  • How about when the third is absent? Example in seq 8 | awk ..., should 7 and 8 printed? – cuonglm Jan 8 '16 at 7:30
4

You can use a variable to track if the previous line is present or not:

$ awk '
  FNR % 3 == 1 {f = $0; next}  # The first line keep in f, skip to next line
  FNR % 3 && f {print f;print} # Previous line present, print it and current line
' <file
this line 1 no un1x
this lines 22 0
but not 1
THIS is not

Or with sed:

sed -ne 'N;/\n/p;N;d' <file
  • Thanks, i don't get how the last line is eliminated from printing what I see that the f contains first line of two consecutive lines and next just moves to next line which be empty so condition is false.Please explain – asadz Jan 8 '16 at 7:37
  • This approach just delay the print of the first line, it's only printed if and only if there is a second. If there is no second line, then nothing is print. – cuonglm Jan 8 '16 at 7:39

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.