#!/usr/bin/perl
# The Missing Textutils, Ondrej Bojar, obo@cuni.cz
# http://www.cuni.cz/~obo/textutils
#
# 'skiplinecmd' is used to launch a specified command in a pipeline but
# circumvent it for the first --skip=X lines. Useful for all the command that
# operate on pipe but do not support --skip=X themselves.
#
# $Id: skiplinecmd,v 1.4 2005/10/10 07:33:50 bojar Exp $

$| = 1;

use Getopt::Long;
$skip = 1;
GetOptions("skip=i"=>\$skip);

$cmdline = shift;

$head = "";
$nr = 0;
while (<>) {
  $nr++;
  $head .= $_;
  last if $nr >= $skip;
}

print STDERR "Executing: $cmdline\n";

$tmpfile = "tmp.$$.skipline";

open CMD, "|$cmdline > $tmpfile" || die "Cannot launch $cmdline";
while (<>) {
  print CMD $_;
}
close CMD || die "Failed to close $cmdline";

print $head;
open TMP, "$tmpfile" || die "Tmpfile $tmpfile lost!";
print while <TMP>;
close TMP;

system "rm $tmpfile";
