2 added 6 characters in body
source | link

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  $bdone
     s  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

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

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
1
source | link

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