]> Tony Duckles's Git Repositories (git.nynim.org) - dotfiles.git/blob - bin/gxpr
bin/git-branch-dates: Smarter automatic line truncation
[dotfiles.git] / bin / gxpr
1 #!/bin/sh
2 # Usage: gxpr <expression>
3 # Like expr(1), but uses Google's calculator to evaluate <expression>.
4 #
5 # Math examples:
6 # $ gxpr '1 + 1'
7 # 2
8 #
9 # $ gxpr 2 ^ 16
10 # 65536
11 #
12 # $ gxpr '(2 ^ 1) + (2 ^ 2) + (2 ^ 3) + (2 ^ 5)'
13 # 46
14 #
15 # $ gxpr '5*9+(sqrt 10)^3='
16 # 76.6227766
17 #
18 # Conversion examples:
19 # $ gxpr 1GB in KB
20 # 1048576 kilobytes
21 #
22 # $ gxpr 10 megabits in megabytes
23 # 1.25 megabytes
24 #
25 # $ gxpr 2 miles in inches
26 # 126720 inches
27
28 CURL='curl -s --header User-Agent:gxpr/1.0'
29 SEARCH="http://www.google.com/search"
30 EXPR=$(echo "$@" | sed -e 's/+/%2B/g' -e 's/ /+/g')
31
32 res=$(
33 $CURL "$SEARCH?q=$EXPR" |
34 grep '<h2 class=r' |
35 perl -pe 's@.*<h2 class=r.*?<b>.*?= (.*?)</b>.*@\1@' |
36 perl -pe 's@\x{a0}@@g' |
37 perl -pe 's@ </font>@@g' |
38 perl -pe 's@<.*?>@@g'
39 )
40
41 # if we don't have a result, assume it's an invalid expression
42 test -z "$res" && {
43 echo "invalid expression:" "$@" 1>&2
44 exit 1
45 }
46
47 echo "$res"