Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uppercase first character in a variable with bash

Tags:

bash

People also ask

How do you uppercase first letter in bash?

@CMCDragonkai: To lowercase the first letter, use "${foo,}" . To lowercase all the letters, use "${foo,,}" . To uppercase all the letters, use "${foo^^}" .

How do you capitalize variables in bash?

You can convert the case of the string more easily by using the new feature of Bash 4. '^' symbol is used to convert the first character of any string to uppercase and '^^' symbol is used to convert the whole string to the uppercase.

How do you capitalize a word in bash?

To convert a string to uppercase in Bash, use tr command. tr stands for translate or transliterate. With tr command we can translate lowercase characters, if any, in the input string to uppercase characters.

What does $() mean in bash?

Dollar sign $ (Variable) The dollar sign before the thing in parenthesis usually refers to a variable. This means that this command is either passing an argument to that variable from a bash script or is getting the value of that variable for something.


One way with bash (version 4+):

foo=bar
echo "${foo^}"

prints:

Bar

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

One way with sed:

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

Prints:

Bar

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

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


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

Using awk only

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