Skip to content

Instantly share code, notes, and snippets.

@ayubmalik
Last active January 27, 2024 19:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ayubmalik/149e2c7f28104f61cc1c862fe9834793 to your computer and use it in GitHub Desktop.
Save ayubmalik/149e2c7f28104f61cc1c862fe9834793 to your computer and use it in GitHub Desktop.
Bash script using Google Translate API to translate English to Spanish using curl and sed only. You can change the 'sl' and 'tl' (source/target language) query parameter to whatever you want. Optionally if you create a symlink and call it 'en' it will translate back to spanish
#!/bin/bash
# uncomment and fix with appropriate values if you are behind a proxy
#export https_proxy='http://localhost:3128'
sl=en
tl=$(basename $0)
if [[ "${tl}" != "es" ]]; then
sl=es
fi
base_url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sl}&tl=${tl}&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'
qry=$( echo $@ | sed -E 's/\s{1,}/\+/g' )
full_url=${base_url}${qry}
response=$(curl -sA "${ua}" "${full_url}")
echo ""
#print only first translation from JSON
echo ${response} | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1
@alexdbsas
Copy link

function gtr {
  sl='auto'
  tl=$1
  shift
  base_url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=$>
  ua='Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Fi>
  qry=$(printf "%s" "$@" | xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g')
  full_url=${base_url}${qry}
  response=$(curl -sA "${ua}" "${full_url}")
  echo "${response}" | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1
}

for non-english locales

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment