2016-04-07 39 views
0

我在shell腳本中迭代數組,並且當條件匹配時,即如果發現'b'想從數組中刪除該元素。我沒有使用索引位置來遍歷。我的數組值(A B C)當shell腳本中的條件匹配時,從數組中刪除元素

我的代碼是

for h in $Arr 
do 
    echo -e "Value of current element $h.\n" 

    if [ $h == "b" ] 
    then 
     echo -e "Delete it\n" 

    else 
     echo -e "Stay here\n" 
    fi 
done 

如何刪除「B」,這樣,當打印我的陣列應該打印(一三)條件匹配時?

回答

0

您可以使用接受的值構建一個臨時數組Brr,然後將它的值分配給Arr

Arr=" a b c" 
Brr="" 
for h in $Arr 
do 
    echo -e "Value of current element $h.\n" 
    if [ $h == "b" ] 
    then 
    echo -e "Delete it\n" 
    #do not add it to Brr 
    else 
    echo -e "Stay here\n" 
    # add it to Brr the temp array 
    Brr="${Brr} $h" 
    fi 
done 
Arr="${Brr}" 
echo $Arr