shell中大寫小轉換


用tr需要新增變量,用declare或typeset需要在變量賦值前或者賦值后單獨聲明,都有些麻煩

此方法為bash 4.0以后新增,bash 4.0 2009年發布

$ test="abcDEF"

# 把變量中的第一個字符換成大寫

$ echo ${test^}
AbcDEF

# 把變量中的所有小寫字母,全部替換為大寫
$ echo ${test^^}
ABCDEF

# 把變量中的第一個字符換成小寫
$ echo ${test,}
abcDEF

# 把變量中的所有大寫字母,全部替換為小寫
$ echo ${test,,}
abcdef


https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

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

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

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
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM