Translate from command line, using google translate ajax API


/ Published in: Bash
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env bash
  2. # gtranslate.sh
  3. # Translate using Google Translate Ajax API:
  4. # http://ajax.googleapis.com/ajax/services/language/translate?v=1.0 \
  5. # &langpair=en|es&q=hello+world
  6. # More Info: http://code.google.com/apis/ajaxlanguage/documentation/
  7. # ksaver (at identi.ca), March 2010.
  8. # Licence: Public Domain Code.
  9.  
  10. progname=$(basename $0)
  11.  
  12. if [ -z "$3" ]
  13. then
  14. echo -e "Usage: $progname lang1 lang2 'string of words to translate...'"
  15. echo -e "Example: $progname en es 'Hello World!'\n"
  16. exit
  17. fi
  18.  
  19. FROM="$1"
  20. TO="$2"
  21.  
  22. # Google Translate Ajax API Url
  23. TRANSURL='http://ajax.googleapis.com/ajax/services/language/translate?v=1.0'
  24. LANGPAIR="$FROM|$TO"
  25. shift 2
  26.  
  27. # Parse string to translate, change ' ' to '+'
  28. # STRING: String to translate.
  29. PSTRING=$(echo "$STRING" |tr ' ' '+')
  30.  
  31. # Get translation
  32. RESPONSE=$(/usr/bin/env curl -s -A Mozilla \
  33. $TRANSURL'&langpair='$LANGPAIR'&q='$PSTRING)
  34.  
  35. echo -n "$progname> "
  36. # Parse and clean response, to show only translation.
  37. echo "$RESPONSE" |cut -d ':' -f 3 |cut -d '}' -f 1

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.