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
?
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 2The \l\1
will turn the Group 1 value to lower case and \U\2
will turn the value in Group 2 to upper case.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With