Search code examples
zsh

replace characters in Zsh variable


I am trying to replace all the - chars with _ chars in a specific variable. Tried to use the tr function. What am I missing?

Thanks!

user@mbp-user ~ % echo $APP_ID
app1_someinfo_info-text_text-indfo_text
user@mbp-user ~ % APP_ID= $APP_ID tr - _
zsh: command not found: app1_someinfo_info-text_text-indfo_text
user@mbp-user ~ % APP_ID= $APP_ID tr "-" "_"
zsh: command not found: app1_someinfo_info-text_text-indfo_text
user@mbp-user ~ % 

Solution

  • You can do this without invoking any other processes.

    $ APP_ID=app1_someinfo_info-text_text-indfo_text
    $ echo $APP_ID
    app1_someinfo_info-text_text-indfo_text
    $ echo ${APP_ID//-/_}
    app1_someinfo_info_text_text_indfo_text
    

    Or reassign to the same variable

    $ APP_ID=${APP_ID//-/_}
    

    Specifically we are using the pattern

    name//pattern/string
    

    which replaces all occurrences of pattern with string in the variable name.