I want to change the case of the n-th letter of a string in BASH (or any other *nix tools, e.g. sed, awk, tr, etc).

I know that you can change the case a whole string using:

${str,,} # to lowercase
${str^^} # to uppercase

Is it possible to change the case of the 3rd letter of "Test" to uppercase?

$ export str="Test"
$ echo ${str^^:3}

In bash you could do:

$ str="abcdefgh"
$ foo=${str:2};echo ${str:0:2}${foo^}

In Perl:

$ perl -ple 's/(?<=..)(.)/uc($1)/e; ' <<<$str


$ perl -ple 's/(..)(.)/$1.uc($2)/e; ' <<<$str
  • 1
    What is purpose of ~ in perl solution? – cuonglm Nov 16 '14 at 5:15
  • @cuonglm a typo. It was left over from a previous versin I tried where I was using $ARGV[0]=~ instead of <<<$str. Thanks. – terdon Nov 16 '14 at 12:16
  • 2
    The bash can be shortened with foo=${str:2} and ${foo^}, which only capitalizes the first character in the string. – chepner Nov 16 '14 at 15:51

With GNU sed (possibly others)

sed 's/./\U&/3' <<< "$str"

With awk

awk -vFS= -vOFS= '{$3=toupper($3)}1' <<< "$str"

Another perl:

$ str="abcdefgh"
$ perl -pe 'substr($_,2,1) ^= " "' <<<"$str"
  • The general form is substr($_,n,1) where n is the position of letter you want to invert the case (0-based index).

  • When you xor an ASCII character with space, you invert its case.

  • That's really cool, I didn't know that xor-ing an ascii character with space inverts its case. – ryanmjacobs Nov 16 '14 at 7:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.