misc/scripts/wa

42 lines
1.2 KiB
Plaintext
Raw Permalink Normal View History

2020-07-25 17:38:45 +02:00
#!/bin/sh
2018-08-05 18:53:07 +02:00
## WolframAlpha CLI
# load api key
2020-07-25 17:38:45 +02:00
token="$XDG_CONFIG_HOME/wolfram"
. "$token"
2018-08-05 18:53:07 +02:00
# properly encode query
2020-07-25 17:38:45 +02:00
q=$(echo "$*" | sed 's/+/%2B/g' | tr '\ ' '\+')
2018-08-05 18:53:07 +02:00
# fetch and parse result
2020-07-25 17:38:45 +02:00
result="$(curl -s "http://api.wolframalpha.com/v2/query?input=$q&appid=$API_KEY&format=plaintext")"
2018-08-05 18:53:07 +02:00
2020-07-25 17:38:45 +02:00
if echo "$result" | grep -q 'Invalid appid'; then
2018-08-05 18:53:07 +02:00
echo "Invalid API key!"
echo "Get one at https://developer.wolframalpha.com/portal/apisignup.html"
2020-07-25 17:38:45 +02:00
printf 'Enter your WolframAlpha API key:'
read -r api_key
echo "API_KEY=${api_key}" >> "$token"
2018-08-05 18:53:07 +02:00
exit 1
fi
2020-07-25 17:38:45 +02:00
echo "$result" |
tr '\n' '\t' |
sed -e 's/<plaintext>/\n<plaintext>/g' |
grep -oE "<plaintext>.*</plaintext>|<pod title=.[^\']*" |
sed -e 's!<plaintext>!!g' \
-e 's!</plaintext>!!g' \
-e 's!<pod title=.*!\x1b[1;36m&\x1b[0m!g' \
-e 's!^! !g' \
-e 's!<pod title=.!\n!g' \
-e 's!\&amp;!\&!g' \
-e 's!\&lt;!<!g' \
-e 's!\&gt;!>!g' \
-e 's!\&quot;!"!g' \
-e "s/\&apos;/'/g" |
tr '\t' '\n' |
sed -e '/^$/d;' \
-e 's/\ \ */\ /g;' \
-e 's/\\\:/\\\u/g'