Skip to content

Instantly share code, notes, and snippets.

@xuchunyang
Last active August 29, 2015 14:12
Show Gist options
  • Save xuchunyang/84e5655b48790d430652 to your computer and use it in GitHub Desktop.
Save xuchunyang/84e5655b48790d430652 to your computer and use it in GitHub Desktop.
google-trans-cn-curl.sh
#!/bin/bash
#
# Filename: google-trans-cn-curl.sh
# Program: Access https://translate.google.cn/ from command line by 'curl(1)'
# Usage: ./google-trans-cn-curl.sh <text>
#
text="$1"
if [[ -z "$text" ]]; then
echo "Usage: $0 <word>"
exit 1
fi
# Detect language (English or Chinese) by the first character's ASCII code, like isalpha(3)
head=${text:0:1}
if [[ "$head" = "a" ]] || [[ "$head" = 'z' ]] || [[ "$head" > "a" ]] && [[ "$head" < "z" ]]; then
sl="en" # Source Language code
tl="zh-CN" # Translation language code
elif [[ "$head" = "A" ]] || [[ "$head" = 'Z' ]] || [[ "$head" > "A" ]] && [[ "$head" < "Z" ]]; then
sl="en" # Source Language code
tl="zh-CN" # Translation language code
else # Detect Chinese, translate to English
sl="zh-CN"
tl="en"
fi
# Encode URL
text=${text/ /+}
translation=$(curl --silent \
"http://translate.google.cn/translate_a/t?client=t&ie=UTF-8&oe=UTF-8&sl=${sl}&tl=${tl}&text=${text}" -H \
'accept-encoding: gzip, deflate, sdch' -H \
'accept-language: en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2' -H \
'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36' -H \
'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' -H \
'x-client-data: CI22yQEIorbJAQiptskBCMS2yQEI8YjKAQjFlMoB' --compressed |
sed 's/[^"]*"\([^"]*\)".*/\1/')
echo "$text => $translation"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment