【问题标题】:How to convert a string to lower case in Bash, when the string is potentially -e, -E or -n? [duplicate]当字符串可能是-e,-E或-n时,如何在Bash中将字符串转换为小写? [复制]
【发布时间】:2025-11-25 00:45:01
【问题描述】:

在这个问题中:How to convert a string to lower case in Bash?

接受的答案是:

tr:

echo "$a" | tr '[:upper:]' '[:lower:]'

awk:

echo "$a" | awk '{print tolower($0)}'

如果 $a 是 -e 或 -E 或 -n,这些解决方案都不起作用

这会是更合适的解决方案吗:

echo "@$a" | sed 's/^@//' | tr '[:upper:]' '[:lower:]'

【问题讨论】:

标签: string bash shell lowercase


【解决方案1】:

使用

printf '%s\n' "$a" | tr '[:upper:]' '[:lower:]'

【讨论】:

    【解决方案2】:

    不要打扰tr。由于您使用的是 bash,因此只需在参数扩展中使用 , 运算符即可:

    $ a='-e BAR'
    $ printf "%s\n" "${a,,?}"
    -e bar
    

    【讨论】:

      【解决方案3】:

      使用typeset(或declare)可以定义一个变量,在赋值给变量时自动将数据转换为小写,例如:

      $ a='-E'
      $ printf "%s\n" "${a}"
      -E
      
      $ typeset -l a                 # change attribute of variable 'a' to automatically convert assigned data to lowercase
      $ printf "%s\n" "${a}"         # lowercase doesn't apply to already assigned data
      -E
      
      $ a='-E'                       # but for new assignments to variable 'a'
      $ printf "%s\n" "${a}"         # we can see that the data is 
      -e                             # converted to lowercase
      

      如果您需要保持当前变量的大小写敏感性,您可以随时定义一个新变量来保存小写值,例如:

      $ typeset -l lower_a
      $ lower_a="${a}"               # convert data to lowercase upon assignment to variable 'lower_a'
      $ printf "%s\n" "${lower_a}"
      -e
      

      【讨论】: