我在bash中有一个数组。
WHITELIST=(
"THIS"
"examPle"
"somTHing"
)
如何在现有数组或新数组中将所有元素转换为小写?
答案 0 :(得分:7)
您可以一次性转换整个数组:
WHITELIST=( "${WHITELIST[@],,}" )
printf "%s\n" "${WHITELIST[@]}"
this
example
somthing
答案 1 :(得分: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.
答案 2 :(得分: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