ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Hi all, this request essentially illustrates my weakness with shell scripts. I have a script that reads in a string that will be in CamelCase and I want to convert the value into first lowercase and then uppercase with an underscore inserted at each Capital letter, after the first appearance, hence:
TestCaseVariable
will become:
test_case_variable
and
TEST_CASE_VARIABLE
I'm sure that there is an easy way to do this in bash, but I need someone to help me find it, many thanks.
Distribution: approximately NixOS (http://nixos.org)
Posts: 1,900
Rep:
It is not to be done in bash itself. It is to be passed to sed (man sed).
a=$(sed -e 's/\([A-Za-z]\)\([A-Z]\)/\l\1_\2/g' <<<$b);
will probably do. There's L and one there, be careful.
Actually there are two other ways to do this 'better' than with sed. Using psed or a single line of perl works, but calling tr is faster and uses less memory than either sed or perl.
I believe that the most recent versions of ksh have some of this capability built in. It may be only a matter of time before it is implemented in bash as an internal.
You're right! Folding case is in the latest bash as documented here (scroll down to the last expansions). IDK which version it's in, maybe 4+?
It is indeed a 4.x feature, however it's not useful for going from TestCaseVariable to test_case_variable. The problem is in inserting the _ properly. It is, however, useful for going from test_case_variable to TEST_CASE_VARIABLE.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.