replace characters in Bash 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 ~ % 

4 answers

  • answered 2022-05-04 10:13 philiptomk

    Try the following:

    [user@host ~]$ APP_ID="app1_someinfo_info-text_text-indfo_text"
    [user@host ~]$ APP_ID=$(echo $APP_ID | tr "-" "_")
    [user@host ~]$ echo $APP_ID
    app1_someinfo_info_text_text_indfo_text
    

  • answered 2022-05-04 10:13 Itagaki Fumihiko

    Try as below

    echo $APP_ID | tr -- - _
    

    To prevent arguments beginning with - from being interpreted as optional arguments, use -- to indicate the end of optional arguments.

    Postscript

    But that didn't matter. tr - _ works as expected. The problem is that you didn't give a string for the standard input of tr.

  • answered 2022-05-04 10:13 HatLess

    Using sed

    $ sed 's/-/_/g' <<< "$APP_ID"
    app1_someinfo_info_text_text_indfo_text
    

    Pure bash

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

    Using awk

    $ awk '{gsub(/-/,"_")}1' <<< "$APP_ID"
    app1_someinfo_info_text_text_indfo_text
    

  • answered 2022-05-04 10:19 Paul Rooney

    You can do this in pure bash, 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.

    For more details see section 5.18 of the Bash Cookbook by Carl Albing.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum