Skip to content
Advertisement

linux shell title case

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])/u2/g"

Advertisement

Answer

a GNU sed one-liner

echo something-that-is-hyphenated | 
sed -e 's/-([a-z])/u1/g' -e 's/^[a-z]/u&/'

u in the replacement string is documented in the sed manual.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement