new tool
[hband-tools.git] / tabdata / td-add-headers
blob926262b0fc4e308953e9b087fd9a848abb063f78
1 #!/usr/bin/env perl
3 =pod
5 =head1 NAME
7 td-add-headers - Add headers to the tabular data stream and pass through the rows.
9 =head1 SYNOPSIS
11 td-add-headers I<COLNAME_1> I<COLNAME_2> ...
13 =head1 DESCRIPTION
15 Add header row to the tabular data stream. Headers names will be the
16 ones specified in the command line arguments, from the left-most 1-by-1.
18 If there are more fields in the first data row, then additional columns
19 will be added with names like "COL4", "COL5", etc. by the index number
20 of the column counting from 1.
21 This may be prevented by --no-extra-columns option.
23 =head1 OPTIONS
25 =over 4
27 =item -x, --extra-columns
29 Give a name also to those columns which are not given name in the command parameters.
31 =item -X, --no-extra-columns
33 Do not add more columns than specified in the command parameters.
35 =back
37 =head1 EXAMPLE
39 who | td-trans | td-add-headers USER TTY DATE TIME COMMENT
41 =cut
43 $OptAddExtraColumns = 1;
44 %OptionDefs = (
45 'x|extra-columns' => sub { $OptAddExtraColumns = 1; },
46 'X|no-extra-columns' => sub { $OptAddExtraColumns = 0; },
49 no if ($] >= 5.018), 'warnings' => 'experimental::smartmatch';
50 do '/usr/lib/tool/perl5/tabdata/common.pl' or die "$@";
52 @Headers = @ARGV;
54 if($OptAddExtraColumns)
56 # complete the number of headers to be as many as fields are there in the first row.
58 $first_line = <STDIN>;
59 chomp $first_line;
60 $num_fields = scalar split $FS, $first_line;
61 for my $n ((1 + scalar @Headers)..$num_fields)
63 push @Headers, "COL$n";
66 else
68 $first_line = undef;
71 print join($FS, @Headers).$RS;
72 print $first_line.$RS if defined $first_line;
73 while(<STDIN>)
75 print;