uppercase first character in a variable with bash

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

    To capitalize first word only:

    foo='one two three'
    foo="${foo^}"
    echo $foo
    

    One two three


    To capitalize every word in the variable:

    foo="one two three"
    foo=( $foo ) # without quotes
    foo="${foo[@]^}"
    echo $foo
    

    One Two Three


    (works in bash 4+)

    0 讨论(0)
  • 2020-12-04 07:24

    This one worked for me:

    Searching for all *php file in the current directory , and replace the first character of each filename to capital letter:

    e.g: test.php => Test.php

    for f in *php ; do mv "$f" "$(\sed 's/.*/\u&/' <<< "$f")" ; done
    
    0 讨论(0)
  • 2020-12-04 07:27
    $ foo="bar";
    $ foo=`echo ${foo:0:1} | tr  '[a-z]' '[A-Z]'`${foo:1}
    $ echo $foo
    Bar
    
    0 讨论(0)
  • 2020-12-04 07:27

    It can be done in pure bash with bash-3.2 as well:

    # First, get the first character.
    fl=${foo:0:1}
    
    # Safety check: it must be a letter :).
    if [[ ${fl} == [a-z] ]]; then
        # Now, obtain its octal value using printf (builtin).
        ord=$(printf '%o' "'${fl}")
    
        # Fun fact: [a-z] maps onto 0141..0172. [A-Z] is 0101..0132.
        # We can use decimal '- 40' to get the expected result!
        ord=$(( ord - 40 ))
    
        # Finally, map the new value back to a character.
        fl=$(printf '%b' '\'${ord})
    fi
    
    echo "${fl}${foo:1}"
    
    0 讨论(0)
  • 2020-12-04 07:28

    One way with bash (version 4+):

    foo=bar
    echo "${foo^}"
    

    prints:

    Bar
    
    0 讨论(0)
  • 2020-12-04 07:29

    This works too...

    FooBar=baz
    
    echo ${FooBar^^${FooBar:0:1}}
    
    => Baz
    
    FooBar=baz
    
    echo ${FooBar^^${FooBar:1:1}}
    
    => bAz
    
    FooBar=baz
    
    echo ${FooBar^^${FooBar:2:2}}
    
    => baZ
    

    And so on.

    Sources:

    • Bash Manual: Shell Parameter Expansion
    • Full Bash Guide: Parameters
    • Bash Hacker's Wiki Parameter Expansion

    Inroductions/Tutorials:

    • Cyberciti.biz: 8. Convert to upper to lower case or vice versa
    • Opensource.com: An introduction to parameter expansion in Bash
    0 讨论(0)
提交回复
热议问题