Wednesday, October 27, 2021

[SOLVED] sed regex - convert Title Case to camelCase

Issue

I have some text which may have either "Regular sentence case" or "Title Case Text", and I want to convert them to titleCaseText.

Taking the example This Is Not the Real string with the sed command

s/(^|\s)([A-Za-z])/\U\2/g

I get the output

ThisIsNotTheRealString

How can I make the first T to be lowercase t?


Solution

You may match the first uppercase letter with ^([A-Z]):

sed -E 's/^([A-Z])|[[:blank:]]+([A-Za-z])/\l\1\U\2/g'

Or

sed -E 's/^([[:upper:]])|[[:blank:]]+([[:alpha:]])/\l\1\U\2/g'

Then, turn the Group 1 value to lower case, and the second group (as you are already doing) to upper case. See the online demo.

Details

  • ^([[:upper:]]) - match the start of the line and then capture an uppercase letter into Group 1
  • | - or
  • [[:blank:]]+ - match 1 or more horizontal whitespace chars
  • ([[:alpha:]]) - and then capture any letter into Group 2

The \l\1 will turn the Group 1 value to lower case and \U\2 will turn the value in Group 2 to upper case.



Answered By - Wiktor Stribiżew