15

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.

Community
  • 1
  • 1
James Oravec
  • 19,579
  • 27
  • 94
  • 160
  • 5
    I know this is old, but if you start the string with a capital letter, it's called PascalCase not camelCase. Just for anyone else finding this. – wesm Jan 15 '21 at 23:48

2 Answers2

31

GNU sed

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")

Perl

It's almost identical in perl:

perl -pe 's/(^|-)(\w)/\U$2/g'

Native bash

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"
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • 3
    The bash solution does not work on Mac with default bash 3.2.57. Perl seems the most portable way. – wlnirvana Aug 06 '20 at 01:40
  • The `sed` version isn't working for me. – Noel Yap Nov 22 '22 at 19:34
  • 1
    @NoelYap are you using GNU sed? Running `sed` with no arguments should give you a clue. If not, it's unlikely to work, since it uses a few extensions that aren't available in other versions. The Perl version is more portable. – Tom Fenech Nov 22 '22 at 22:04
-7

its very easy

   $string='this-is-a-string' ;

   echo   str_replace('-', '', ucwords($string, "-"));

output ThisIsAString

Abbbas khan
  • 306
  • 2
  • 15
  • I'm sorry but isn't this PHP instead of bash? I believe the poster was asking for bash. – Fons Sep 01 '20 at 12:01