[Solved] How to lowercase and replace spaces in bash? [closed]


Requires bash4 (tested with 4.3.48).

Assuming you never want a upper case character in the value of the variable output, I would propose the following:

typeset -l output
output=${input// /_}
  • typeset -l output: Defines the variable to be lowercase only. From man bash:

    When the variable is assigned a value, all upper-case characters are converted to lower-case.

  • output=${input// /_}: replaces all spaces with a underscore.

BTW: There is also typeset -u variable to define it as “all upercase”.
See man bash.


Update: While revisiting, I realized that my answer matches the question question title, but not the PHP code. In the PHP example, all characters that are not a-z are replaced with a underscore. So, if input contains a colon or a comma, those would also be replaced by underscore.

So here is code that also matches that:

typeset -l output
output=${input//[^a-z]/_}

Finally a quote from the answer of @micha-wiedenmann :

One thing to note though is that the BASH version uses patterns instead of regular expressions. For example, the pattern * is similar to the regular expression .*. And the pattern ? is ..

Check the man-page and search for “Pattern Matching”.

5

solved How to lowercase and replace spaces in bash? [closed]