Skip to content

Instantly share code, notes, and snippets.

@marendowski
Created October 29, 2023 14:24
Show Gist options
  • Save marendowski/814e66ce1f03a981a213ee040b84828f to your computer and use it in GitHub Desktop.
Save marendowski/814e66ce1f03a981a213ee040b84828f to your computer and use it in GitHub Desktop.
Use google translate to translate words or sentences using dmenu
#!/bin/sh
cmd=$(dmenu_path | dmenu "$@")
case $cmd in
# translate e.g. `en:es hello world` -> translate hello world to spanish
*:* ) lang1=$(echo $cmd | cut -d':' -f1);
lang2=$(echo $cmd | cut -d':' -f2 | cut -d' ' -f1);
query=$(echo $cmd | cut -d':' -f2 | awk '{for(i=2;i<=NF;i++) print $i}'); # get query after `es:en `
query=$(echo $query | sed -E 's/\s{1,}/\+/g'); # substitute spaces for `+`
base_url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=${lang1}&tl=${lang2}&dt=t&q="
ua='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
full_url=${base_url}${query}
response=$(curl -sA "${ua}" "${full_url}")
translated=`echo ${response} | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1` # clean up the request
echo $translated | dmenu;;
* ) ${cmd};;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment