O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  



Command Line Calculator
Calculate from the command line thanks to Google and PHP.

Contributed by:
Adam Trachtenberg
[09/09/03 | Discuss (10) | Link to this hack]

This two line PHP script lets you use the Google calculator from your command line.

#!/usr/bin/php
<?php
preg_match_all('{<b>.+= (.+?)</b>}', 
  file_get_contents('http://www.google.com/search?q=' . 
     urlencode(join(' ', array_splice($argv, 1)))), $matches);
print str_replace('<font size=-2> </font>', ',',
  "{$matches[1][0]}\n");
?>

To install, save it in a file in a directory in your PATH and run "chmod +x" to make it executable. It's invoked like this:

% calc 21 * 2
42

% calc 26 ounces + 1 pint in ounces
42 US fluid ounces

% calc answer to life, the universe and everything
42

If your shell gives you a parse error, place the calculation inside quotation marks.

There's absolutely no error checking in this Hack, so if you enter something that Google doesn't think is a calculation, then you'll likely get a PHP Notice. Likewise, if Google changes its HTML output, the regex could fail. But if this was more robust, it'd no longer be a hack.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.