2017-04-12 80 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