Change case of n-th letter in a string

5,995

Solution 1

In bash you could do:

$ str="abcdefgh"
$ foo=${str:2}  # from the 3rd letter to the end
echo ${str:0:2}${foo^} # take the first three letters from str and capitalize the first letter in foo.
abCdefgh

In Perl:

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

Or

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

Solution 2

With GNU sed (possibly others)

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

With awk

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

Solution 3

Another perl:

$ str="abcdefgh"
$ perl -pe 'substr($_,2,1) ^= " "' <<<"$str"
abCdefgh
  • 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.

Share:
5,995

Related videos on Youtube

A Yashwanth
Author by

A Yashwanth

Hi there. My name is Ryan Jacobs and I make stuff. If you want to learn more about what I do, visit ryanjacobs.io.

Updated on September 18, 2022

Comments

  • A Yashwanth
    A Yashwanth almost 2 years

    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}
    TeSt
    
  • cuonglm
    cuonglm over 9 years
    What is purpose of ~ in perl solution?
  • terdon
    terdon over 9 years
    @cuonglm a typo. It was left over from a previous versin I tried where I was using $ARGV[0]=~ instead of <<<$str. Thanks.
  • chepner
    chepner over 9 years
    The bash can be shortened with foo=${str:2} and ${foo^}, which only capitalizes the first character in the string.