Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spinal Case to Camel Case

Tags:

bash

sed

My question is pretty much the opposite of this: linux bash, camel case string to separate by dash

Pretty much looking to take some-string-like-this to SomeStringLikeThis.

Anyone got some sed magic or other means of doing this easily?

As a side note, part of me thinks that as popular as Bash is, that there might be a library out there that could help with conversions like this... I haven't found one though. If you know of one, please let me know. e.g. a library that would handle common string manipulations/conversion between standard naming styles, such as spinal to underscore, underscore to camel, camel to spinal, etc.

like image 704
James Oravec Avatar asked Dec 22 '15 16:12

James Oravec


People also ask

What is CamelCase example?

/ˈkæm. əl ˌkeɪs/ the use of a capital letter to begin the second word in a compound name or phrase, when it is not separated from the first word by a space: Examples of camel case include "iPod" and "GaGa." See also.

What's the opposite of CamelCase?

When multiple words are used to form a variable, camel case joins those words together, without any white space, and delineates the start of each new word with a capital letter. In contrast, snake case uses an underscore between words to create separation.

What is Spinal case?

spinal-case is a variant of snake-case which uses hyphens “-” to separate words. The pros and cons are quite similar to those of snake-case, with the exception that some languages do not allow hyphens in symbol names (for variable, class, or function naming).


1 Answers

GNU sed

This works with GNU sed:

sed -r 's/(^|-)(\w)/\U\2/g'

Match the start of the line or a - followed by an alphanumeric character and use \U to make the character uppercase.

And here's how you can operate on a variable with it and assign the result to another variable:

name_upper=$(sed -r 's/(^|-)(\w)/\U\2/g' <<<"$name_spinal")

Perl

It's almost identical in perl:

perl -pe 's/(^|-)(\w)/\U$2/g'

Native bash

Just for fun, here's a way you could do it in native bash:

spinal_to_upper() {
    IFS=- read -ra str <<<"$1"
    printf '%s' "${str[@]^}"
}

spinal_to_upper "some-string-like-this"
like image 65
Tom Fenech Avatar answered Sep 30 '22 23:09

Tom Fenech