uppercase first character in a variable with bash

前端 未结 15 1762
一整个雨季
一整个雨季 2020-12-04 07:01

I want to uppercase just the first character in my string with bash.

foo=\"bar\";

//uppercase first character

echo $foo;

should print \"B

15条回答
  •  孤城傲影
    2020-12-04 07:40

    What if the first character is not a letter (but a tab, a space, and a escaped double quote)? We'd better test it until we find a letter! So:

    S='  \"ó foo bar\"'
    N=0
    until [[ ${S:$N:1} =~ [[:alpha:]] ]]; do N=$[$N+1]; done
    #F=`echo ${S:$N:1} | tr [:lower:] [:upper:]`
    #F=`echo ${S:$N:1} | sed -E -e 's/./\u&/'` #other option
    F=`echo ${S:$N:1}
    F=`echo ${F} #pure Bash solution to "upper"
    echo "$F"${S:(($N+1))} #without garbage
    echo '='${S:0:(($N))}"$F"${S:(($N+1))}'=' #garbage preserved
    
    Foo bar
    = \"Foo bar=
    

提交回复
热议问题