baggiponte
baggiponte

Reputation: 726

Parameter Expansion in Zsh vs Bash: what is the equivalent of "${VAR,,}"?

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.

Upvotes: 1

Views: 641

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

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

Upvotes: 5

iodine
iodine

Reputation: 41

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.

Upvotes: 1

Related Questions