Top
Convert camelCase to Underscores Using sed (mod) – Dragos Cirjan
fade
158
post-template-default,single,single-post,postid-158,single-format-standard,flow child-child-ver-1.0.0,flow-ver-1.3.6,,eltd-smooth-page-transitions,ajax,eltd-blog-installed,page-template-blog-standard,eltd-header-standard,eltd-fixed-on-scroll,eltd-default-mobile-header,eltd-sticky-up-mobile-header,eltd-dropdown-default

Warning: A non-numeric value encountered in /usr/src/wordpress/wp-content/themes/flow/framework/modules/title/title-functions.php on line 417

Convert camelCase to Underscores Using sed (mod)

Convert camelCase to Underscores Using sed (mod)

This short post deals with converting strings of the form camelCase or CamelCase into camel_case, and vice versa. This is an update for the article Convert camelCase to Underscores Using sed.

I discovered Amir did not think that variables may have numbers in them, so here it is a more complete version, I hope:

Convert CamelCase or camelCase to camel_case:

sed -e 's/([A-Z0-9])/_\l\1/g' -e 's/^_([a-z0-9])/\l\1/g' file.txt
echo "camelCase" | sed -e 's/([A-Z0-9])/_\l\1/g' -e 's/^_([a-z0-9])/\l\1/g'

Convert camel_case to camelCase

sed -e 's/_([a-z0-9])/\u\1/g' file.txt
echo "camel_case" | sed -e 's/_([a-z0-9])/\u\1/g'

Convert camel_case to CamelCase:

sed -e 's/_([a-z0-9])/\u\1/g' -e 's/^([a-z0-9])/\u\1/g' file.txt
echo "camel_case" | sed -e 's/_([a-z0-9])/\u\1/g' -e 's/^([a-z0-9])/\u\1/g'

Please notice the new 0-9 element added to all regular expressions. You should still be careful of what variable you choose to transform considering there may be problems with variable naming rules for the programming language you use.

NOTE: Please note that I did not test all new formulas and they may not work. If they don”t or you have new modifications, please notify me.

Cirjan Dragos
No Comments

Post a Comment