uppercase first character in a variable with bash

Bash

Bash Problem Overview


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

foo="bar";

//uppercase first character

echo $foo;

should print "Bar";

Bash Solutions


Solution 1 - Bash

One way with bash (version 4+):

foo=bar
echo "${foo^}"

prints:

Bar

Solution 2 - Bash

foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"

Solution 3 - Bash

One way with sed:

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

Prints:

Bar

Solution 4 - Bash

$ foo="bar";
$ foo=`echo ${foo:0:1} | tr  '[a-z]' '[A-Z]'`${foo:1}
$ echo $foo
Bar

Solution 5 - Bash

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+)

Solution 6 - Bash

Using awk only

foo="uNcapItalizedstrIng"
echo $foo | awk '{print toupper(substr($0,0,1))tolower(substr($0,2))}'

Solution 7 - Bash

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

Solution 8 - Bash

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&/'

Solution 9 - Bash

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

Solution 10 - Bash

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:

Inroductions/Tutorials:

Solution 11 - Bash

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

Solution 12 - Bash

Alternative and clean solution for both Linux and OSX, it can also be used with bash variables

python -c "print(\"abc\".capitalize())"

returns Abc

Solution 13 - Bash

first-letter-to-lower () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[A-Z]' '[a-z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}
first-letter-to-upper-xc () {
        v-first-letter-to-upper | xclip -selection clipboard
}
first-letter-to-upper () {
        str="" 
        space=" " 
        for i in $@
        do
                if [ -z $(echo $i | grep "the\|of\|with" ) ]
                then
                        str=$str"$(echo ${i:0:1} | tr  '[a-z]' '[A-Z]')${i:1}$space" 
                else
                        str=$str${i}$space 
                fi
        done
        echo $str
}

first-letter-to-lower-xc(){ v-first-letter-to-lower | xclip -selection clipboard }

Solution 14 - Bash

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

Solution 15 - Bash

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=

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchovyView Question on Stackoverflow
Solution 1 - BashSteveView Answer on Stackoverflow
Solution 2 - BashMichael HoffmanView Answer on Stackoverflow
Solution 3 - BashSteveView Answer on Stackoverflow
Solution 4 - BashMajid LaissiView Answer on Stackoverflow
Solution 5 - BashOle LukøjeView Answer on Stackoverflow
Solution 6 - BashtoskeView Answer on Stackoverflow
Solution 7 - BashEquin0xView Answer on Stackoverflow
Solution 8 - BashFreemanView Answer on Stackoverflow
Solution 9 - BashMichał GórnyView Answer on Stackoverflow
Solution 10 - BashzetaomegagonView Answer on Stackoverflow
Solution 11 - BashShemesheyView Answer on Stackoverflow
Solution 12 - BashThomas DucrotView Answer on Stackoverflow
Solution 13 - Bashuser123456View Answer on Stackoverflow
Solution 14 - BashIvanView Answer on Stackoverflow
Solution 15 - BashRogerView Answer on Stackoverflow