HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Command line tools to format tables

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
formattableslinecommandtools

Problem

I am a big fan of one-liners using sed awk perl and other tools. But there are that are things hard to do in one-liner, such as when you working with a CSV file and there are commas between quotes, or when you want to print a centralized field with printf.

A few months ago I wrote ftable more for fun than anything else, but last weekend I took it seriously and created a GitHub repository and a tutorial for it.

ftable tutorial

ftable code

Questions

Do you know of a tool that's similar to ftable? I hate feeling like re-inventing the wheel.

As I am not programmer (I am sysadmin/devops). Is there anybody willing to review the code and spot my endless mistakes?

```
#! /usr/bin/env perl
# Author: Tiago Lopo Da Silva
# Date: 20/10/2013
# Purpose: Print formatted table

use strict;
use warnings;
use POSIX;
use Switch;
use Getopt::Long qw(:config no_ignore_case);
use Data::Dumper;

our $comma="";
our $dollar="";
our $pipe="|";
our $plus="+";
our $minus="-";
our $FS=',';
our $nb=0;

my %h;
if ($#ARGV >= 0){
my $lf; my $cf; my $rf; my $print;

GetOptions( 'l|left:s' => \$lf,
'r|right:s' => \$rf,
'c|center:s' => \$cf,
'p|print:s' => \$print,
'F:s' => \$FS,
'n|noborder' => \$nb,
) || print_usage();

%h=get_details($lf,$cf,$rf,$print);
}else {
%h=get_details();
}
print_table(\%h);

sub get_quoted_fields {
# this sub finds quoted fields
my $str1 = $_[0];
my $qf;
while ( $str1 =~ /(["'].*?["'])/ ){
$qf.="$1${comma}";
$str1 =~ s/$1//;
}
return $qf;
}

sub get_translated {
my $qf = $_[0];
my $str= $_[1];
my @arr;
my %h;

if (defined ($qf)) {
@arr = split(/$comma/,$qf);
}

foreach my $i ( @arr ){
my $tmpvar=$i;
$i =~ s/$FS/$comma/g;
$h{$tmpvar} = $i;
}

while ( my($key,$value) = each(%h) ){
$key =~ s/\$/\\\$/g;
eval "\$str =~ s/$key/$value/g; ";
}

return

Solution

column(1) is a Unix tool with a similar purpose, but does not draw box borders using ASCII art.

There may not be a standard command to draw tables with box borders, but as always, there's a CPAN module for that. As for parsing the input, there's a CPAN module for that too. By taking advantage of CPAN, you can avoid reinventing-the-wheel and discard most of your code.

Context

StackExchange Code Review Q#51765, answer score: 4

Revisions (0)

No revisions yet.