Shell 技巧:大小写, strtoupper, strtolower, ucwords, ucword

1. strtoupper

echo "justcode.ikeepstudying" | tr '[:lower:]' '[:upper:]'
#JUSTCODE.IKEEPSTUDYING

 

其他方法:

echo 'justcode.ikeepstudying.com' | awk '{print toupper($0)}'
#JUSTCODE.IKEEPSTUDYING
echo "justcode.ikeepstudying.com" | tr /a-z/ /A-Z/
#JUSTCODE.IKEEPSTUDYING.COM
$ tr [a-z] [A-Z] < convert_to_uppercase.txt
#JUSTCODE.IKEEPSTUDYING
$ string="justcode.ikeepstuding.com"
$ echo "${string^}"
#Justcode.ikeepstuding.com

$ echo "${string^^}"
#JUSTCODE.IKEEPSTUDING.COM

$ echo "${string^^[aeiou]}"
#jUstcOdE.IkEEpstUdIng.cOm

$ string="JustCode.iKeepStudying.com"
$ declare -u string
$ string=$string; echo "$string"
#JUSTCODE.IKEEPSTUDING.COM

 

2. strtolower

"JUSTCODE.IKEEPSTUDYING" | tr '[:upper:]' '[:lower:]'
#justcode.ikeepstudying

 

其他方法:

The are various ways:

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
justcode.ikeepstudying.com

 

AWK

$ echo "$a" | awk '{print tolower($0)}'
justcode.ikeepstudying.com

 

Bash 4.0

$ echo "${a,,}"
justcode.ikeepstudying.com

 

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
justcode.ikeepstudying.com
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
justcode.ikeepstudying.com

 

Perl

$ echo "$a" | perl -ne 'print lc'
justcode.ikeepstudying.com

Bash

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

 

3. ucwords

echo 'justcode ikeepstudying com is my own site !' | tr " " "\n" | nawk ' { out = out" "toupper(substr($0,1,1))substr($0,2) } END{ print substr(out,2) } '
#Justcode Ikeepstudying Com Is My Own Site !

 

4. ucword
$ string="justcode.ikeepstuding.com"
$ echo "${string^}"
#Justcode.ikeepstuding.com
sed 's/\(.\)/\U\1/' <<< "justcode.ikeepstudying.com is my own site!"
#Justcode.ikeepstudying.com is my own site!

 

其他:

#Toggle (undocumented, but optionally configurable at compile time)

$ 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


#Capitalize (undocumented, but optionally configurable at compile time)

$ string="a few words"
$ declare -c string
$ string=$string
$ echo "$string"
A few words
Title case:

$ 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"

 

参考:

Shell:AWK 简明教程, AWK 入门教程, AWK 格式化输出, AWK 过滤记录, AWK 符串匹配, AWK 折分文件, AWK 分割字符串等实例

Linux Shell脚本入门教程系列之(五)Shell字符串

Linux Shell系列教程之(二十) Shell 脚本中一些特殊符号:# ; ;; . , / \\ ‘string’| ! $ ${} $? $$ $* \”string\”* ** ? : ^ $# $@ `command`{} [] [[]] () (()) || && {xx,yy,zz,…}~ ~+ ~- & \\ + – %= == !=

 

One Comment

Leave a Reply