所以我有一个名为“名词”的文件,如下所示:
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语句? 谢谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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