1

Is there a builtin way in KornShell to capitalize a word, e.g. korn -> Korn? A Bash 4 example to clarify:

str='korn'
echo "${str^}"

If there is not a bultin way to do this in KornShell, what is the most concise and efficient way to write a function that will do it?

2
  • bash can do this with M-c (typically, Alt-c) at the beginning of the word. No idea about ksh though.
    – jw013
    Jul 16, 2012 at 15:04
  • 2
    @Kazark, better specify whether you want editing or scripting functionality. My understanding was that you want something like str='korn'; echo "${str^}" in bash. But after @jw013's comment I am not so sure.
    – manatwork
    Jul 16, 2012 at 15:08

3 Answers 3

3

Here is a pure ksh (ksh93) way:

function cap {
    typeset -u f
    f=${1:0:1}
    printf "%s%s\n" "$f" "${1:1}"
}

$ cap korn
Korn
1
  • Not excessively verbose. +1 ...I didn't know the syntax for string slicing, so that is helpful.
    – Kazark
    Jul 16, 2012 at 20:56
3

If you don't have ksh93 available, you can do it in standard ksh like this:

function capitalize { 
  typeset -u first
  first=${1%"${1#?}"}
  print "${first}${1#?}"

}

${1#?} strips all characters matching "?" from the beginning of the first arg. i.e. strips off the first character

${var%pattern} strips off pattern from the end of var. If we use the original word minus the first letter as the pattern (${1#?}), we get the first letter back.

typeset -u turns the first letter uppercase

$ capitalize "the funky chicken"
The funky chicken

Caveat, this actually doesn't always work since you could have special regex characters after the first letter of the word and they will be interpreted as such by ${var%pattern}. e.g.

$ capitalize a*
A**
1
  • you might want print -- .... I can't recall how ksh's print handles -options.
    – mikeserv
    Feb 9, 2015 at 18:22
0
% str='korn'
% echo ${(U)str:0:1}${str#?} 
Korn

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .