2017-04-12 81 views
1

製作卡片所以我有一個所謂的「名詞」的文件,看起來像這樣:與「選擇」命令

English word:matching Spanish word 
Englsih word:matching Spanish word 
..etc etc 

我需要一個程序,列出所有的英語單詞有選擇退出。程序顯示英文單詞並詢問用戶他想翻譯的單詞,並且他還可以鍵入「退出」退出。

這是我迄今爲止,顯示我的英文

列表
select english in $(cut -d: -f1 nouns) 

do 
if [ "$english" = 'quit' ] 
then 
exit 0 
fi 
done 

我知道我需要運行通過搜索相應的英文拉起第二列(-f2)命令這樣的詞

result=$(grep -w $english nouns|cut -d: -f2) 

我的最終結果應該只是把相應的西班牙語單詞。我只是不知道如何讓所有的部分合在一起。我知道它基於一種「if」格式(我認爲),但我是否爲grep行開始單獨的if語句? 謝謝

回答

1

你需要一個循環,你要求用戶輸入。剩下的就是把正確的控制流程放在一起。見下面我的代碼:

while : 
do 
    read -p "Enter word (or quit): " input 

    if [ "$input" = "quit" ]; then 
    echo "exiting ..." 
    break 
    else 
    echo "searching..." 
    result=$(grep $input nouns | cut -d ':' -f 2) 
    if [[ $result ]]; then 
     echo "$result" 
    else 
     echo "not found" 
    fi 
    fi 
done 
0

你想在一個恆定的while loop如果用戶輸入來運行這個,只有breaking the loop「跳槽」。從用戶using read獲取輸入以將其放入一個變量中。至於搜索,這可以通過awk(其設計用於使用這樣的分隔文件)或grep相當容易地完成。

#!/bin/sh 
while true; do 
    read -p "Enter english word: " word 
    if [ "$word" = "quit" ]; then 
     break 
    fi 

# Take your pick, either of these will work: 
# awk -F: -v "w=$word" '{if($1==w){print $2; exit}}' nouns 
    grep -Pom1 "(?<=^$word:).*" nouns 
done 
0
dfile=./dict 

declare -A dict 
while IFS=: read -r en es; do 
    dict[$en]=$es 
done < "$dfile" 

PS3="Select word>" 
select ans in "${!dict[@]}" "quit program"; do 
case "$REPLY" in 
    [0-9]*) w=$ans;; 
    *) w=$REPLY;; 
esac 

case "$w" in 
    quit*) exit 0;; 
    *) echo "${dict[$w]}" ;; 
esac 

done