3

How can I get a translated string, e.g. English to Spanish, from Google Translate with some command line tools like curl? I looked at the page source but Google Translate doesn't seem to include the translation result in its html source even though the result is rendered on the screen. So

 curl "https://translate.google.com/#auto/es/stay%20calm"

didn't work--just gave me the html source that doesn't have either original string or translated one. And I heard that their API was not free so I don't want to use it. I hear that there's also Microsoft's translation service, but I'd like to stick to Google's if possible.

stacko
  • 791
  • 1
    I suspect that they make it difficult to use their service outside of a browser with Javascript (you're supposed to use the API if you want to do that). You may need to use something more sophisticated than curl. If so the answers here should help. – Gilles 'SO- stop being evil' Jun 27 '16 at 21:18

1 Answers1

3

You may create this function in your ~/.bashrc

function gtr {
  sl=en
  tl=$1
  shift
  base_url="https://translate.googleapis.com/translate_a/single?client=gtx&sl=$sl&tl=$tl&dt=t&q="
  ua='Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0'
  qry=$( echo "$*" | sed -e "s/\ /+/g" )
  full_url=$base_url$qry
  response=$(curl -sA "$ua" "$full_url")
  echo "$response" | sed 's/","/\n/g' | sed -E 's/\[|\]|"//g' | head -1
}
Usage
$: gtr es hi this is a test 
Hola esto es una prueba

Source

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
San Juan
  • 31
  • 3