Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed regex - convert Title Case to camelCase

Tags:

regex

sed

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?

like image 491
Hanxue Avatar asked Mar 07 '23 02:03

Hanxue


2 Answers

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.

like image 189
Wiktor Stribiżew Avatar answered Mar 09 '23 15:03

Wiktor Stribiżew


one way is to use two different substitutions

$ s='This Is Not the Real string'
$ echo "$s" | sed -E 's/^[A-Z]/\l&/; s/\s([A-Za-z])/\u\1/g'
thisIsNotTheRealString

$ s='Regular sentence case'
$ echo "$s" | sed -E 's/^[A-Z]/\l&/; s/\s([A-Za-z])/\u\1/g'
regularSentenceCase

if you have mixed case input:

$ s='ReGulAr sEntEncE cASe'
$ echo "$s" | sed -E 's/^[a-zA-Z]+/\L&/; s/\s([A-Za-z]+)/\L\u\1/g'
regularSentenceCase
like image 30
Sundeep Avatar answered Mar 09 '23 17:03

Sundeep