0

I am passing a set of 6 arguments initially to a script.

Script.sh a b c d e f

One of the commands in the script which is managing the arguments;

comm=$(echo $1 |sed 's/~/ /g')
Kusalananda
  • 333,661
  • 1
    Imho, some at least basic research should be done before asking questions. You can find the answer in the info text of sed tag which has been used in this question. https://unix.stackexchange.com/tags/sed/info – pLumo Nov 28 '18 at 13:28

1 Answers1

14

The sed expression s/~/ /g replaces every tilde with a space character. It means, literally, "substitute everything that matches the regular expression ~ with a space, globally (on the whole input line)". The expression could in this case also have been written as the quicker y/~/ /, and the whole sed command could be replaced by the even faster tr '~' ' '.

In bash, this is more efficiently done with

comm=${1//\~/ }

The ~ has to be escaped or quoted here to not be expanded to the pathname of the current user's home directory.

In any case, the $1 needs to be double quoted if you are using it with echo (unless you want shell globs to be expanded to filenames), and ideally, the command would be written with printf (this avoids an initial dash in $1 from being interpreted as the start of some option to echo, and avoids having certain backslash sequences interpreted under some circumstances):

comm=$( printf '%s\n' "$1" | tr '~' ' ' )

Related:

Kusalananda
  • 333,661
  • Re: "globally (on the whole input line)": where can I find it in man sed? I see only "g G - Copy/append hold space to pattern space." Is this what I'm looking for? – pmor May 24 '23 at 09:59
  • 1
    @pmor The g here is a "flag" for the s command, so you should be looking at the documentation for the s command. The g and G commands are not the same thing. – Kusalananda May 24 '23 at 10:21
  • Thanks! Now I see: "g Apply the replacement to all matches to the regexp, not just the first." – pmor May 24 '23 at 11:23