3

我在 bash 中有一个数组。

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

如何将现有数组或新数组中的所有元素转换为小写?

4

3 回答 3

9

您可以一次性转换整个数组:

WHITELIST=( "${WHITELIST[@],,}" )
printf "%s\n" "${WHITELIST[@]}"
this
example
somthing
于 2013-06-21T02:27:01.493 回答
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.
于 2013-06-21T02:01:36.807 回答
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
于 2013-06-21T02:08:58.567 回答