如何在Bash中将字符串从大写转换为小写? [英] How to convert a string from uppercase to lowercase in Bash?
问题描述
我一直在寻找一种将字符串值从大写转换为小写的方法.所有搜索结果均显示使用tr
命令的方法.
I have been searching to find a way to convert a string value from upper case to lower case. All the search results show approaches of using tr
command.
tr
命令的问题在于,仅当我将命令与echo语句一起使用时,我才能获得结果.例如:
The problem with the tr
command is that I am able to get the result only when I use the command with echo statement. For example:
y="HELLO"
echo $y| tr '[:upper:]' '[:lower:]'
上面的方法在'hello'中起作用并导致结果,但是我需要将结果分配给如下所示的变量:
The above works and results in 'hello', but I need to assign the result to a variable as below:
y="HELLO"
val=$y| tr '[:upper:]' '[:lower:]'
string=$val world
像上面那样分配值时,它给我一个空的结果.
When assigning the value like above it gives me an empty result.
PS:我的Bash版本是3.1.17
PS: My Bash version is 3.1.17
推荐答案
如果您使用的是bash 4,则可以使用以下方法:
If you are using bash 4 you can use the following approach:
x="HELLO"
echo $x # HELLO
y=${x,,}
echo $y # hello
z=${y^^}
echo $z # HELLO
仅使用一个,
或^
来使第一个字母lowercase
或uppercase
.
Use only one ,
or ^
to make the first letter lowercase
or uppercase
.
这篇关于如何在Bash中将字符串从大写转换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!