Ad Hoc Data Analysis From The Unix Command Line/Appendices

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Appendix A: pcalc source code[edit | edit source]

A perl read-eval-print loop. This makes a very handy calculator on the command line. Example usage:

$ pcalc 1+2
3
$ pcalc "2*2"
4
$ pcalc 2*3
6

Source:

#!/opt/third-party/bin/perl
use strict;
if ($#ARGV >= 0) {
  eval_print(join(" ",@ARGV))
} else { 
  use Term::ReadLine;
  my $term = new Term::ReadLine 'pcalc';
  while ( defined ($_ = $term->readline("")) ) {
    s/[\r\n]//g;
    eval_print($_);
    $term->addhistory($_) if /\S/;
  }
}

sub eval_print {
  my ($str) = @_;
  my $result = eval $str;
  if (!defined($result)) {
    print "Error evaluating '$str'\n";
  } else {
    print $result,"\n";
  }
}

Appendix B: Random unfinished ideas[edit | edit source]

Ideas too good to delete, but that aren't fleshed out.

Micro shell scripts from the command line[edit | edit source]

Example - which .so has the object I want?

Using backticks[edit | edit source]

Example - killing processes by name[edit | edit source]

kill `ps auxww | grep httpd | grep -v grep | awk '{print $2}'`

Example - tailing the most recent log file in one easy step[edit | edit source]

tail -f `ls -rt *log | tail -1`

James' xargs trick[edit | edit source]

James uses echo with xargs and feeds one xargs' output into another xargs in clever ways to build up complex command lines.

tee(1)[edit | edit source]

perl + $/ == agrep[edit | edit source]

Example - Finding duplicate keys in two files[edit | edit source]

Quick Plotting With gnuplot