Friday, June 24, 2011

Converting first characters to capital in a string variable - BASH

Let's say you have a variable that contains a string of text, and you need the first characters to be capitalized. This quick how to will show you just that.

My variable is set as follow:

$ var="this is a text title"

$ echo $var
this is a text title

 Bash has built-in variable substitution that will convert a matching pattern (see the man page for either bash or bash-bultins for more info).

${parameter^pattern}
${parameter^^pattern}

Here's a simplified usage:

$ var=test

$ echo ${var^t} # Could also be ${var^}
Test

 So for my first example, we can add the same parameter substitution to a for loop, and here's what we get:

$ var="this is a text title"
 
$ echo $var
this is a text title
 
$ for i in `echo $var` ; do echo ${i^} ; done | tr '\n' ' ' ; echo -e "\r"
This Is A Text Title

 

2 comments:

iNack said...

var=test
echo ${var^^}
Result:
TEST

iNack said...

All capital:

$ var=test
$ echo ${var^^}
TEST
$