Sed regex - convert Case to camelCase header

I have text that can have either “Regular Suggestion Case” or “Heading Text”, and I want to convert them to titleCaseText.

Taking This Is Not the Real stringthe sed command example

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

I get a conclusion

ThisIsNotTheRealString

How to make the first Tlowercase T?

+4
source share
2 answers

You can match the first capital 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 change the value of group 1 to lower case, and the second group (as you already do) to upper case. See the online demo .

More details

  • ^([[:upper:]]) - matches the beginning of a line, and then writes an uppercase letter to group 1
  • | - or
  • [[:blank:]]+ - 1
  • ([[:alpha:]]) - 2

\l\1 1 , \U\2 2 .

+3

$ 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

:

$ s='ReGulAr sEntEncE cASe'
$ echo "$s" | sed -E 's/^[a-zA-Z]+/\L&/; s/\s([A-Za-z]+)/\L\u\1/g'
regularSentenceCase
+3

Source: https://habr.com/ru/post/1692567/


All Articles