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.
/ˈ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.
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.
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).
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")
It's almost identical in perl:
perl -pe 's/(^|-)(\w)/\U$2/g'
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"
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