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"
Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
$() – the command substitution. ${} – the parameter substitution/variable expansion.
$# : This variable contains the number of arguments supplied to the script. $? : The exit status of the last command executed. Most commands return 0 if they were successful and 1 if they were unsuccessful. Comments in shell scripting start with # symbol.
#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications.
a GNU sed one-liner
echo something-that-is-hyphenated |
sed -e 's/-\([a-z]\)/\u\1/g' -e 's/^[a-z]/\u&/'
\u
in the replacement string is documented in the sed manual.
Pure bashism:
var0=something-that-is-hyphenated
var1=(${var0//-/ })
var2=${var1[*]^}
var3=${var2// /}
echo $var3
SomethingThatIsHyphenated
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.
You can define a function:
hypenToCamel() {
tr '-' '\n' | awk '{printf "%s%s", toupper(substr($0,0,1)), substr($0,2)}'
}
CAMEL=$(echo something-that-is-hyphenated | hypenToCamel)
echo $CAMEL
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