1

I am trying to perform case modification with bash/zsh parameter expansion on macOS (11.4) and making some mistakes. Specifically, I want to take a variable that contains a string and turn it to snakecase (i.e.: from This is a STRING to this_is_a_string). I am taking baby steps and so far I am just trying to turn everything to lowercase and, as far as I understand it, the theory should work like this:

$ VAR="StRING"
$ echo "${VAR,,}" # turn the string characters to lowercase
string

This did not work at first, because macOS bash is the very much outdated 3.2.57. I installed the current version (5.1.8) with homebrew and it worked.

Still, this does not work with zsh (most recent version). I guess this happens because parameter expansion is different in zsh, am I right? Still, I cannot find any resourceful reference. I believe that zsh works a bit differently, more like sed. Sure, I could use tr and even sed itself, but I wanted to use parameter expansion.

oguz ismail
  • 1
  • 16
  • 47
  • 69
baggiponte
  • 547
  • 6
  • 13
  • 1
    See `man zshexpn` for all the different operations you can use with parameter expansion. (And more generally, `man zshall` to get an overview of all the various man pages documenting `zsh`.) – chepner Jun 01 '21 at 18:03
  • Are you asking how to do this in zsh, or do you want to do it in bash, or are you hoping for a solution that will work in both? – William Pursell Jun 01 '21 at 18:07
  • I was only looking for a solution in zsh (the documentation was not really clear to me and I could not find many tutorials online). But now I guess the safest way of doing that is exploiting `tr` or `sed` for compatibility. – baggiponte Jun 01 '21 at 19:03

2 Answers2

5

In Zsh, you can use expansion modifiers:

echo ${VAR:l}
## => string

To turn the string to upper case, you can use

echo ${VAR:u}
## => STRING

See an online Zsh demo.

Or, you may use expansion flags:

echo ${(L)VAR}
## => string
echo ${(U)VAR}
## => STRING
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

The pattern to convert to lowercase using zsh AND parameter expansion is by using the L flag.

Using your example:

> VAR="StRING"
> echo ${(L)VAR}

However I'm not sure how portable it will be between bash and zsh.

iodine
  • 41
  • 3