First character of a variable in a shell script to uppercase?

You could use

strModuleToTestUpper=`sed 's/\(.\)/\U\1/' <<< "$strModuleToTest"`

Explanation

  • \(.\) matches a single character
  • \U\1 replaces that character with an uppercase version
  • no /g means only the first match is processed.

If:

s=somemodule

with bash v4+

echo ${s^}

This should work with a bit older bash versions (from Glenn):

echo $(tr a-z A-Z <<< ${s:0:1})${s:1}")

with zsh

echo ${(C)s}

with ash and coreutils

echo $(echo $s | cut -c1 | tr a-z A-Z)$(echo $s | cut -c2-)

with GNU sed

echo $s | sed 's/./\U&/'

with BSD sed

echo $s | sed '
  h;
  y/quvwxzdermatoglyphicsbfjkn/QUVWXZDERMATOGLYPHICSBFJKN/;
  G;
  s/\(.\)[^\n]*\n.\(.*\)/\1\2/;
'

with awk

echo $s | awk '{ print toupper(substr($0, 1, 1)) substr($0, 2) }'

with perl

echo $s | perl -nE 'say ucfirst'

with python

echo $s | python -c 'import sys; print sys.stdin.readline().rstrip().capitalize()'

with ruby

echo $s | ruby -e 'puts ARGF.read.capitalize'

Output in all cases

Somemodule

Is perl ok?

$ x=foobar
$ x=$(echo "$x" | perl -pe 's/^(.)/uc($1)/e')
$ echo $x
Foobar

Tags:

Unix

Shell

Awk

Sed