dl() {
# Read text from stdin
local text=$(cat -)
# Set the API endpoint and your Deepl API key
local endpoint="https://api-free.deepl.com/v2/translate"
local api_key="$your_deepl_api_key"
local target_lang="EN"
# Set the target language to English
local out=$(curl -s -X POST "$endpoint" -H "Content-Type: application/x-www-form-urlencoded" -d "auth_key=$api_key&text=$text&target_lang=$target_lang")
local language=$(echo $out | jq -r '.translations[0].detected_source_language')
# Set the target language based on the detected language
if [ "$language" = "EN" ]; then
local target_lang="ZH"
local out=$(curl -s -X POST "$endpoint" -H "Content-Type: application/x-www-form-urlencoded" -d "auth_key=$api_key&text=$text&target_lang=$target_lang")
fi
# Extract the translated text from the API response using jq
echo "$out" | jq -r '.translations[0].text'
}
Usage:
$ echo '你好世界' | dl
Hello World
$ echo 'Hello World' | dl
你好,世界