2017-07-28 4 views
1

私は選択項目を作成したい項目と呼ばれるフラットファイルを持っていますが、一度に複数の項目を選択できるようにします。アイテムのbash複数の回答を一度に選択

内容をファイル:

cat 1 
dog 1 
pig 1 
cherry 2 
apple 2 

Basicスクリプト:

#!/bin/bash 
PS3=$'\n\nSelect the animals you like: ' 
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }') 

select choice in $options 
do 
    echo "you selected: $choice" 
done 

exit 0 

を、それが今流れ道は、私は一度に1つのオプションを選択できます。私は1,3または1 3に答えて、それが応答しているできるようにしたいのですが、「あなたが選択した:猫の豚」

ありがとう、

をTazmarine

+0

「選択」ではこれを行うことは不可能です。 –

答えて

0

となるようにメニューループを作成する必要があります。これは私が思いついたものです。これは私が望むように動作するようです。最終出力をコンマで区切って入力します。

#!/bin/bash 

newarray=(all $(grep '1' items|grep -v '^#' |awk '{ print $1 }')) 

options() { 
num=0 
for i in ${newarray[@]}; do 
    echo "$num) $i" 
    ((num++)) 
done 
} 

getanimal() { 
while [[ "$show_clean" =~ [A-Za-z] || -z "$show_clean" ]]; do 
    echo "What animal do you like: " 
    options 
    read -p 'Enter number: ' show 
    echo 
    show_clean=$(echo $show|sed 's/[,.:;]/ /g') 
    selected=$(\ 
    for s in $show_clean; do 
    echo -n "\${newarray[${s}]}," 
    done) 
    selected_clean=$(echo $selected|sed 's/,$//') 
done 
eval echo "You selected $selected_clean" 
} 

getanimal 

exit 0 
1

次のようなことを行うことができません、しかし、あなたは常に、個々の選択を記録することができます:

#!/bin/bash 
PS3=$'\n\nSelect the animals you like: ' 
options=$(grep '1' items|grep -v '^#' |awk '{ print $1 }') 

# Array for storing the user's choices 
choices=() 

select choice in $options Finished 
do 
    # Stop choosing on this option 
    [[ $choice = Finished ]] && break 
    # Append the choice to the array 
    choices+=("$choice") 
    echo "$choice, got it. Any others?" 
done 

# Write out each choice 
printf "You selected the following: " 
for choice in "${choices[@]}" 
do 
    printf "%s " "$choice" 
done 
printf '\n' 

exit 0 

は、ここで例の対話です:

$ ./myscript 
1) cat 
2) dog 
3) pig 
4) Finished 

Select the animals you like: 3 
pig, got it. Any others? 

Select the animals you like: 1 
cat, got it. Any others? 

Select the animals you like: 4 
You selected the following: pig cat 

代わりに3 1を同じ行に書きたい場合は、echoread

+0

アドバイスありがとうございます。私は1 3 4 7または1,3,4,7、あるいは1:3:4:7を使用する能力が必要です。一部のリストは80以上の大きなアイテムになることがありますので、一度に1つずつ選択することは好ましくありません。私はこれについて考え、いくつかのオプションを掲示しなければならないでしょう。項目リストは変わる可能性があるので、最初に数値用の変数を定義し、解析する方法が必要になると思われます。私は火曜日この記事を私が思いついたもので更新します。ありがとうございました。 – tazmarine

関連する問題