2013-06-21 101 views

回答

7

您可以將整個數組轉換在o NE拍攝:

WHITELIST=("${WHITELIST[@],,}") 
printf "%s\n" "${WHITELIST[@]}" 
this 
example 
somthing 
2

您可以使用${parameter,,}

WHITELIST=(
     "THIS" 
     "examPle" 
     "somTHing" 
     ) 

i=0 
for elt in "${WHITELIST[@]}" 
do 
    NEWLIST[$i]=${elt,,} 
    i=$((${i} + 1)) 
done 

for elt in "${NEWLIST[@]}" 
do 
    echo $elt 
done 

從手冊頁:

${parameter,,pattern} 
      Case modification. This expansion modifies the case of alpha‐ 
      betic characters in parameter. The pattern is expanded to pro‐ 
      duce a pattern just as in pathname expansion. The^operator 
      converts lowercase letters matching pattern to uppercase; the , 
      operator converts matching uppercase letters to lowercase. The 
      ^^ and ,, expansions convert each matched character in the 
      expanded value; the^and , expansions match and convert only 
      the first character in the expanded value. If pattern is omit‐ 
      ted, it is treated like a ?, which matches every character. If 
      parameter is @ or *, the case modification operation is applied 
      to each positional parameter in turn, and the expansion is the 
      resultant list. If parameter is an array variable subscripted 
      with @ or *, the case modification operation is applied to each 
      member of the array in turn, and the expansion is the resultant 
      list. 
+0

良好的解決方案,但只'bash的4.x'。 –

+1

*聳肩*和? :)'tr'(你的答案)是一個很好的回退。 –

+1

不要誤解我的意思,我只是覺得讓OP知道防止不必要的心痛不能執行一個非常好的解決方案會很好。 :) –

0

一個這樣做的方式:

$ WHITELIST=("THIS" "examPle" "somTHing") 
$ x=0;while [ ${x} -lt ${#WHITELIST[*]} ] 
    do WHITELIST[$x]=$(tr [A-Z] [a-z] <<< ${WHITELIST[$x]}) 
    let x++ 
done 
$ echo "${WHITELIST[@]}" 
this example somthing 
+1

loopless種類可能會改變'WHITELIST'中的元素數量,並受字詞拆分的影響。 – chepner

+0

@chepner你是對的!如果你不介意,你能解釋爲什麼發生這種情況嗎? –

+1

'tr'將輸入作爲單個字符串讀取,失去了一個元素停止和下一個開始的位置的任何概念。輸出同樣是一個單一的文本字符串,shell根據IFS的當前值將字符分割爲單詞以設置WHITELIST的新值。總之,'tr'不知道數組,所以不能保持元素之間的區別。 – chepner

相關問題