Search This Blog

Thursday, December 23, 2010

Perl script options

Using getopt in perl scripts.
Sample code
#!/usr/bin/perl
#-------------------------------------------------------------------------
#       Using getop
#-------------------------------------------------------------------------
use Getopt::Std;
getopt('cw');
my @op = `./x.sh -c $opt_c -w $opt_w`;
foreach (@op)
{
        #printf "-c %s\t-w %s\n", $opt_c,$opt_w;
        print $_;
}

Output
./x.pl -c 3 -w 55
in ./x.sh.sh : -c 3 -w 55
-c 3
-w 55

or

my %options=();
#Pre set default values 
my $critv=95;
my $warnv=85;
getopts("c:w:", \%options);
$critv = $options{c} if defined $options{c};
$warnv = $options{w} if defined $options{w};

This method won't report an error if an option is emitted.

Wednesday, December 01, 2010

awk convert time string to time format

This will take a time string HHMMSS (121525) and format it as 12:15:25

A sample line from a.txt:

01201 095440 sd10 3393.2 1.1 13572.8 4.4 0.0 1.0 0.3 2 91

awk '{h=substr($2,1,2);\
      m=substr($2,3,2);\
      s=substr($2,5,2);\
      $2=sprintf("%s:%s:%s",h,m,s);\
      print $0;}' a.txt | head 
 

Will produce the following out put:

101201 09:54:40 sd10 3393.2 1.1 13572.8 4.4 0.0 1.0 0.3 2 91