gxpr

09 May 2013 in Tech

Today's utility is a little bash script that searches Google and returns the value
that Google Calculator supplies. If Google Calculator can't work out the answer, it
delegates and gives you a link to Wolfram Alpha.

Example

Whilst the script is called gxpr, I've simply called it g as it's easier to type.

bash
# It can do simple maths
vagrant:~$ g 1+1
2
# And it can do conversions
vagrant:~$ g 3984588 bytes in mb
3.79999924 megabytes
# It can even answer questions
vagrant:~$ g speed of light in mph
670616629 mph
# But sometimes it doesn't know, and asks Wolfram
# When this happens, control/option-click the link to open it
vagrant:~$ g 1368035948 unixtime
"google doesn't know 1368035948 unixtime"
⌘ click: http://www.wolframalpha.com/input/?i=1368035948%20unixtime

The script

If you want to use g, you'll need to create a file called "g", copy the following script into it and make sure that the file you created is somewhere in your $PATH and that you run chmod a+x on it to make it executable.

bash
#!/bin/sh
CURL='curl -s --header User-Agent:gxpr/1.0'
GOOGLE="http://www.google.com/ig/calculator"
WOLFRAM="http://www.wolframalpha.com/input/"
EXPR=$(echo "$@" | perl -MURI::Escape -ne 'chomp;print uri_escape($_)')
res=$(
$CURL "$GOOGLE?q=$EXPR" |
perl -ne '/rhs: "?([^\[\],":]+)/ and print $1' |
perl -pe 's/[^\x00-\x7F]//g'
)
# if we don't have a result, try wolfram alpha
test -z "$res" && {
echo "google doesn't know" "$@" 1>&2
echo "⌘ click: \033[4m$WOLFRAM?i=$EXPR\033[0m"
exit 1
}
echo "$res"

gxpr on GitHub via pengwynn