如何在Bash中将字符串转换为小写?
有没有在bash中将字符串转换为小写字符串的方法?
例如,如果我有:
a="Hi all"
我想将它转换为:
"hi all"
有多种方式:
TR
$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
AWK
$ echo "$a" | awk '{print tolower($0)}'
hi all
Bash 4.0
$ echo "${a,,}"
hi all
SED
$ echo "$a" | sed -e 's/(.*)/L1/'
hi all
# this also works:
$ sed -e 's/(.*)/L1/' <<< "$a"
hi all
Perl的
$ echo "$a" | perl -ne 'print lc'
hi all
巴什
lc(){
case "$1" in
[A-Z])
n=$(printf "%d" "'$1")
n=$((n+32))
printf $(printf "%o" "$n")
;;
*)
printf "%s" "$1"
;;
esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
ch="${word:$i:1}"
lc "$ch"
done
在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"
要关闭declare
属性,请使用+
。 例如, declare +c string
。 这会影响后续分配,而不会影响当前值。
declare
选项更改变量的属性,但不更改内容。 我的示例中的重新分配更新内容以显示更改。
编辑:
按照ghostdog74的建议添加了“按字切换第一个字符”( ${var~}
var〜 ${var~}
)。
编辑:修正了代字符的行为来匹配Bash 4.3。
echo "Hi All" | tr "[:upper:]" "[:lower:]"
链接地址: http://www.djcxy.com/p/9795.html