我在bash中有一个数组。
WHITELIST=(
"THIS"
"examPle"
"somTHing"
)
我该如何将现有数组中的所有元素转换为小写字母,或者在一个新数组中进行转换?
WHITELIST=( "${WHITELIST[@],,}" )
printf "%s\n" "${WHITELIST[@]}"
this
example
somthing
${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
从man手册中:
${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.
一种做法:
$ 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
WHITELIST
дёӯе…ғзҙ зҡ„ж•°йҮҸпјҢеҸ–еҶідәҺеҚ•иҜҚжӢҶеҲҶгҖӮ - chepnertr
命令将输入作为单个文本字符串读取,丢失任何元素之间的区分。输出同样是一个单独的文本字符串,shell 根据当前 IFS
的值将其拆分成单词,以设置新的 WHITELIST
值。简而言之,tr
不知道数组,因此无法保留元素之间的区别。 - chepner
bash 4.x
。 - jaypal singhtr
(你的答案)是一个很好的备选方案。 - Brian Cainfor elt in "${WHITELIST[@]}"
(包括引号和@
符号)-- 这是唯一安全的方法来保存包含空格的元素。 - glenn jackman