Issue
I would like to convert 2+ words to camel case. I tried in online ubuntu version and it works. But not on mac os.
my amazing-long_variable -> myAmazingLongVariable
echo "my amazing-long_variable" | sed -E 's/[ |_|-]([a-z])/\U\1/gi' | sed -E 's/^([A-Z])/\l\1/'
My Output:
sed: 1: "s/[ |_|-]([a-z])/\U\1/gi": bad flag in substitute command: 'i'
2nd attempt:
echo "my amazing-long_variable" | sed -E 's/[ |_|-]([a-z])/\U\1/g' | sed -E 's/^([A-Z])/\l\1/'
Output:
myUamazingUlongUvariable
Thanks
Solution
\U
and \l
are GNU sed extensions. Perl will work for you out of the box:
echo "my amazing-long_variable" | perl -nE 'say lcfirst join "", map {ucfirst lc} split /[^[:alnum:]]+/'
You read this from right to left
split /[^[:alnum:]]+/
splits the default variable$_
(i.e., the current line) on any sequence of non-alphanumeric characters, resulting in the list "my", "amazing", "long", "variable"map {ucfirst lc}
applies the codeucfirst lc
to each word in turn.- as you might guess,
lc
lower cases the word, thenucfirst
capitalizes the first character - this results in the list "My", "Amazing", "Long", "Variable"
- as you might guess,
join "",
joins the words using the empty string: "MyAmazingLongVariable"lcfirst
lower cases the first character: "myAmazingLongVariable"
The perl option -n
loops over the input file and/or standard input, putting each line in the "default variable" $_
. -l
takes care of handling the line endings for the print command.
Answered By - glenn jackman