Skip to main content
2 of 2
added 6 characters in body
Rakesh Sharma
  • 859
  • 1
  • 5
  • 7

POSIX sed: this method uses the posixly sed and so can be run everywhere, or atleast those seds that respect posix.

 $ sed -ne '
   /\n/!{
    H;s/.*//;x
   }

   :loop
       $bdone
       N;s/\n/&/4
       tdone
   bloop

   :done
   s/.//;P
 ' input.file

Another is a programmatic sed code generation for scalability purposes:

$ code=$(yes n | head -n 4 | paste -sd\; | sed s/n/p/)
$ sed -ne "$code" input.file

Perl: we fill-up array A till it is 4 in size. Then we print its first element and also clear out the array.

$ perl -pe '
   $A[@A] = @A ? <> : $_ while @A < 4;
   $_ = (splice @A)[0];
' input.file
Rakesh Sharma
  • 859
  • 1
  • 5
  • 7