I am wrinting a shell script and have a variable like this: something-that-is-hyphenated
.
I need to use it in various points in the script as:
something-that-is-hyphenated
, somethingthatishyphenated
, SomethingThatIsHyphenated
I have managed to change it to somethingthatishyphenated
by stripping out -
using sed "s/-//g"
.
I am sure there is a simpler way, and also, need to know how to get the camel cased version.
Edit: Working function derived from @Michał's answer
function hyphenToCamel {
tr '-' '\n' | awk '{printf "%s%s", toupper(substr($0,1,1)), substr($0,2)}'
}
CAMEL=$(echo something-that-is-hyphenated | hyphenToCamel)
echo $CAMEL
Edit: Finally, a sed one liner thanks to @glenn
echo a-hyphenated-string | sed -E "s/(^|-)([a-z])/\u\2/g"
In the shell you are stuck with being messy:
Note the carefully placed space in the echo and the double space in the last -e.
I leave it as an exercise to complete the code.
In perl it is a bit easier as a one-line shell command:
a GNU sed one-liner
\u
in the replacement string is documented in the sed manual.For the records, here's a pure Bash safe method (that is not subject to pathname expansion)—using Bash≥4:
This (safely) splits the lowercase expansion of
var0
at the hyphens, with each split part in arrayvar1
. Then we use the^
parameter expansion to uppercase the first character of the fields of this array, and concatenate them.If your variable may also contain spaces and you want to act on them too, change
IFS=-
intoIFS='- '
.You can define a function:
Pure bashism:
Line 1 is trivial.
Line 2 is the bashism for replaceAll or
's/-/ /g'
, wrapped in parens, to build an array.Line 3 uses
${foo^}
, which means uppercase (while${foo,}
would mean 'lowercase' [note, how^
points up while,
points down]) but to operate on every first letter of a word, we address the whole array with${foo[*]}
(or${foo[@]}
, if you would prefer that).Line 4 is again a replace-all: blank with nothing.
Line 5 is trivial again.