Search code examples
shellawksedzsh

sed Capital_Case not working


I'm trying to convert a string that has either - (hyphen) or _ (underscore) to Capital_Case string.

#!/usr/bin/env sh

function cap_case() {
  [ $# -eq 1 ] || return 1;
  _str=$1;
  _capitalize=${_str//[-_]/_} | sed -E 's/(^|_)([a-zA-Z])/\u\2/g'
  echo "Capitalize:"
  echo $_capitalize
  return 0
}

read string
echo $(cap_case $string)

But I don't get anything out.

First I am replacing any occurrence of - and _ with _ ${_str//[-_]/_}, and then I pipe that string to sed which finds the first letter, or _ as the first group, and then the letter after the first group in the second group, and I want to uppercase the found letter with \u\2. I tried with \U\2 but that didn't work as well.

I want the string some_string to become

Some_String

And string some-string to become

Some_String

I'm on a mac, using zsh if that is helpful.


Solution

  • EDIT: More generic solution here to make each field's first letter Capital.

    echo "some_string_other" | awk -F"_" '{for(i=1;i<=NF;i++){$i=toupper(substr($i,1,1)) substr($i,2)}} 1' OFS="_"
    

    Following awk may help you.

    echo "some_string" | awk -F"_" '{$1=toupper(substr($1,1,1)) substr($1,2);$2=toupper(substr($2,1,1)) substr($2,2)} 1' OFS="_"
    

    Output will be as follows.

    echo "some_string" | awk -F"_" '{$1=toupper(substr($1,1,1)) substr($1,2);$2=toupper(substr($2,1,1)) substr($2,2)} 1' OFS="_"
    Some_String