uppercase first character in a variable with bash

前端 未结 15 1600
一整个雨季
一整个雨季 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:30

    Not exactly what asked but quite helpful

    declare -u foo #When the variable is assigned a value, all lower-case characters are converted to upper-case.
    
    foo=bar
    echo $foo
    BAR
    

    And the opposite

    declare -l foo #When the variable is assigned a value, all upper-case characters are converted to lower-case.
    
    foo=BAR
    echo $foo
    bar
    
    0 讨论(0)
  • 2020-12-04 07:33

    Here is the "native" text tools way:

    #!/bin/bash
    
    string="abcd"
    first=`echo $string|cut -c1|tr [a-z] [A-Z]`
    second=`echo $string|cut -c2-`
    echo $first$second
    
    0 讨论(0)
  • 2020-12-04 07:39

    just for fun here you are :

    foo="bar";    
    
    echo $foo | awk '{$1=toupper(substr($1,0,1))substr($1,2)}1'
    # or
    echo ${foo^}
    # or
    echo $foo | head -c 1 | tr [a-z] [A-Z]; echo $foo | tail -c +2
    # or
    echo ${foo:1} | sed -e 's/^./\B&/'
    
    0 讨论(0)
  • 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=
    
    0 讨论(0)
  • 2020-12-04 07:43
    foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"
    
    0 讨论(0)
  • 2020-12-04 07:45

    One way with sed:

    echo "$(echo "$foo" | sed 's/.*/\u&/')"
    

    Prints:

    Bar
    
    0 讨论(0)
提交回复
热议问题