2013-06-21 68 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

相关问题