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?

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

1 Answer 1

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
2
  • 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, 2016 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, 2016 at 7:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .