如何将Bash数组的所有元素转换为小写?

5

我在bash中有一个数组。

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

我该如何将现有数组中的所有元素转换为小写字母,或者在一个新数组中进行转换?

3个回答

12
您可以一次性将整个数组进行转换:
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

从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.

好的解决方案,但仅适用于bash 4.x - jaypal singh
1
耸肩而已,还有什么? :) tr(你的答案)是一个很好的备选方案。 - Brian Cain
1
别误会我的意思,我只是想让OP知道,以防止不能执行一个非常好的解决方案而导致不必要的痛苦。 :) - jaypal singh
1
直到今天我才知道这个功能。我读了问题,想到可能有一种语言特性可以实现它,于是打开了manpage,结果发现了它。我以为它已经存在很久了,所以得知它是最近才出现的,真是太好了。 - Brian Cain
你应该使用for elt in "${WHITELIST[@]}"(包括引号和@符号)-- 这是唯一安全的方法来保存包含空格的元素。 - glenn jackman

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
дёҚдҪҝз”ЁеҫӘзҺҜзҡ„ж–№жі•еҸҜиғҪдјҡжӣҙж”№WHITELISTдёӯе…ғзҙ зҡ„ж•°йҮҸпјҢеҸ–еҶідәҺеҚ•иҜҚжӢҶеҲҶгҖӮ - chepner
@chepner 您是正确的!如果您不介意,能否请您解释一下为什么会发生这种情况? - jaypal singh
1
tr 命令将输入作为单个文本字符串读取,丢失任何元素之间的区分。输出同样是一个单独的文本字符串,shell 根据当前 IFS 的值将其拆分成单词,以设置新的 WHITELIST 值。简而言之,tr 不知道数组,因此无法保留元素之间的区别。 - chepner
非常感谢@chepner。感谢您的解释。 - jaypal singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接