Shell脚本大小写字符串转换


以前写Bash Shell脚本,大小写转换通常这样做:

str="This is a Bash Shell script."

newstr=`tr '[A-Z]' '[a-z]' <<<"$str"`

今天看bash的man page,发现有更简单的方法

转小写,只需要将变量名字declare -l 后,再给变量赋值,变量的内容即为小写
转大写,只需要将变量名字declare -u后,再给变量赋值,变量的内容即为大写

例如:
m="abc"
echo $m # 输出为abc
declare -u m
echo $m # 输出为abc,
m="cde"
echo $m # 输出为CDE
declare -l m="HELL"
echo $m # 输出为hell

注意:
1,declare 不影响变量当前值,而是影响declare之后的赋值

2,通过declare -l/-u进行设置过的变量,可以通过declare +l/+u来取消设置。

3,Bash版本比较低的不行……

相关内容