Skip to content

Instantly share code, notes, and snippets.

@htlin222
Created July 16, 2026 05:00
Show Gist options
  • Select an option

  • Save htlin222/8526020ae12f7048d6460081979913d6 to your computer and use it in GitHub Desktop.

Select an option

Save htlin222/8526020ae12f7048d6460081979913d6 to your computer and use it in GitHub Desktop.
cdict - plain-text CLI wrapper for cdict.net (英漢字典) lookups
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -eq 0 ]]; then
echo "用法: cdict <單字或詞>" >&2
exit 1
fi
term="$*"
html=$(curl -fsSL -A "Mozilla/5.0" -G --data-urlencode "q=${term}" "https://cdict.net/")
# 只取 <pre> 區塊內、第一個字典來源的內容
entry=$(printf '%s\n' "$html" | perl -0777 -ne '
if (/<a name=result><\/a><pre>(.*?)<\/pre>/s) {
my $body = $1;
# 只保留第一個來源,切到第二個來源標記之前
$body =~ s/(<span class=source>.*?<\/span><br>.*?)(<span class=source>.*)/$1/s;
print $body;
}
')
if [[ -z "$entry" ]] || [[ "$entry" == *"沒有發現"* ]]; then
echo "找不到「${term}」的翻譯" >&2
exit 1
fi
printf '%s\n' "$entry" \
| sed -E 's/<[^>]*>//g' \
| perl -CSD -pe '
s/&#x([0-9a-fA-F]+);/chr(hex($1))/ge;
s/&#(\d+);/chr($1)/ge;
s/&amp;/&/g;
s/&lt;/</g;
s/&gt;/>/g;
s/&quot;/"/g;
' \
| sed -E '/^[[:space:]]*$/d' \
| sed -E 's/^[[:space:]]+//'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment