
我想創建一個程式碼來獲得以下結果:
echo -e "\t\tPlease enter your name?"
read name
name="${name,,}"
for i in $(echo "Hello " $name) ; do
echo ${i^}
done | sed 's/^/\t\t/;s/$/, here is your order:/'
如果我輸入以下名稱:mike denver
輸出是:
<here come out the right space of two tabs>Hello, here is your order:
<here come out the right space of two tabs>Mike, here is your order:
<here come out the right space of two tabs>Denver, here is your order:
基本上,它根據我放置的選項卡數量 ( ) 從左側建立右側空間\t
,但它會Hello
為輸入的每個名稱重複列印加號行。我不明白如何將 sed 命令放在外面。我的預期結果應該是這樣的:
<here come out the right space of two tabs>Hello, Mike Denver here is your order:
答案1
與使用循環相比for
,這樣做要容易得多:
echo -e "\t\tPlease enter your name?"
read -a name
name="${name}"
echo -e "\t\tHello ${name[@]^}, here is your order:"
輸出:
Please enter your name?
mike denver
Hello Mike Denver, here is your order:
參數兩邊的雙引號echo
將擴展變數並以所需的格式一次列印所有內容。
答案2
您可以使用數組作為名稱和printf
:
read -p $'\t\tPlease enter your name?\n' -a name
name=( "${name[@],,}" )
printf '\t\tHello %s, here is your order:\n' "${name[*]^}"