5

How can I convert underscore separated words to "camelCase"? Here is what I'm trying:

echo "remote_available_packages" | sed -r 's/([a-z]+)_([a-z])([a-z]+)/\1\U\2\L\3/'

But it returns remoteAvailable_packages without changing the p in packages.

ilkkachu
  • 138,973

3 Answers3

11

This does that (in GNU sed):

echo "remote_available_packages" | sed -E 's/_(.)/\U\1/g'
  • Unfortunately, I don't do perl... – George Udosen Jan 12 '18 at 23:07
  • 2
    You should use -E rather than -r with sed. It's the POSIX standard option for enabling extended regular expressions in sed. The -r option was used by some versions of sed to do the same thing and now exists only for legacy compatibility reasons. -E is the correct, portable form that will work with all modernish versions of sed. -E is also used for the same purpose by grep and other programs. – cas Jan 13 '18 at 03:38
  • Note that on macOS, GNU sed is not the one in /usr/bin/sed – Giuseppe Crinò Jan 07 '20 at 17:11
2

In awk

echo 'remote_available_packages'  | awk -F _ '{printf "%s", $1; for(i=2; i<=NF; i++) printf "%s", toupper(substr($i,1,1)) substr($i,2); print"";}'
1

In Perl:

echo "remote_available_packages" | perl -pe 's/(^|_)([a-z])/uc($2)/ge'  

Or:

echo "remote_available_packages" | perl -pe 's/_([a-z])/uc($1)/ge'

if the first letter should not be capitalized.