bash中有没有将字符串转换为小写字符串的方法?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
bash中有没有将字符串转换为小写字符串的方法?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
当前回答
对于Bash 3.2.+| Mac:
read -p 'What is your email? ' email
email=$(echo $email | tr '[:upper:]' '[:lower:]')
email="$email"
echo $email
其他回答
在Bash 4中:
小写
$ string="A FEW WORDS"
$ echo "${string,}"
a FEW WORDS
$ echo "${string,,}"
a few words
$ echo "${string,,[AEIUO]}"
a FeW WoRDS
$ string="A Few Words"
$ declare -l string
$ string=$string; echo "$string"
a few words
大写
$ string="a few words"
$ echo "${string^}"
A few words
$ echo "${string^^}"
A FEW WORDS
$ echo "${string^^[aeiou]}"
A fEw wOrds
$ string="A Few Words"
$ declare -u string
$ string=$string; echo "$string"
A FEW WORDS
切换(未记录,但可在编译时配置)
$ string="A Few Words"
$ echo "${string~~}"
a fEW wORDS
$ string="A FEW WORDS"
$ echo "${string~}"
a FEW WORDS
$ string="a few words"
$ echo "${string~}"
A few words
大写(未记录,但可在编译时配置)
$ string="a few words"
$ declare -c string
$ string=$string
$ echo "$string"
A few words
标题大小写:
$ string="a few words"
$ string=($string)
$ string="${string[@]^}"
$ echo "$string"
A Few Words
$ declare -c string
$ string=(a few words)
$ echo "${string[@]}"
A Few Words
$ string="a FeW WOrdS"
$ string=${string,,}
$ string=${string~}
$ echo "$string"
A few words
要关闭声明属性,请使用+。例如,声明+c字符串。这会影响后续赋值,而不是当前值。
declare选项更改变量的属性,但不更改内容。示例中的重新分配会更新内容以显示更改。
编辑:
按照ghostdog74的建议,添加了“按单词切换第一个字符”(${var~})。
编辑:更正波浪号行为以匹配Bash 4.3。
使用此命令执行同样的操作,它会将大写字符串转换为小写:
sed 's/[A-Z]/[a-z]/g' <filename>
正则表达式
我想为我想分享的命令而感到自豪,但事实是我从http://commandlinefu.com.它的优点是,如果你cd到你自己的主文件夹中的任何目录,它会递归地将所有文件和文件夹更改为小写,请谨慎使用。这是一个出色的命令行修复程序,特别适用于您存储在驱动器上的大量相册。
find . -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;
您可以指定一个目录来代替查找后的点(.),该点表示当前目录或完整路径。
我希望这个解决方案证明是有用的,但这个命令不能做的一件事是用下划线替换空格-哦,也许下次吧。
echo "Hi All" | tr "[:upper:]" "[:lower:]"
在bash 4中,可以使用类型集
例子:
A="HELLO WORLD"
typeset -l A=$A