[英]How do I translate a list using a dictionary in bash?
說我有一個字典TSV文件dict.txt
:
apple pomme
umbrella parapluie
glass verre
... ...
另一個文件list.txt
包含單詞列表(來自dict.txt
左列):
pie
apple
blue
...
我想將它們翻譯成dict.txt
右欄中的相應單詞,即:
tarte
pomme
bleu
...
最簡單的方法是什么?
您可以使用awk:
awk 'FNR==NR{a[$1]=$2;next} a[$1]{print a[$1]}' dict.txt list.txt
編輯:如果需要使用制表符字段分隔符在字典中將多個單詞(用空格分隔)作為單詞含義,則可以使用:
awk -F '\t' 'FNR==NR{a[$1]=$2;next} a[$1]{print a[$1]}' dict.txt list.txt
如果您沒有很多單詞(以便所有內容都適合存儲在內存中),則可以使用關聯數組:
#!/bin/bash
declare -A english2french=()
# Build dictionary
linenb=0
while ((++linenb)) && IFS=$'\t' read -r en fr; do
if [[ -z $fr ]] || [[ -z $en ]]; then
echo "Error line $linenb: one of the two is empty fr=\`$fr' en=\`$en'"
continue
fi
english2french["$en"]=$fr
done < dict.txt
# Translate
linenb=0
while ((++linenb)) && read -r en; do
[[ -z $en ]] && continue
fr=${english2french["$en"]}
if [[ -n $fr ]]; then
echo "$fr"
else
echo >&2 "Error line $linenb: word \`$en' unknown"
fi
done < list.txt
似乎有點長,但是有很多錯誤檢查;)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.