2

i have this:

echo $MSG | sed -e $'s/;/\\\n/g'

I want to put the result of that sed in a new variable called $MSG2

Something like:

$MSG2=echo $MSG|sed -e $'s/;/\\\n/g'

How can i do it?

Thank you!

muru
  • 72,889

2 Answers2

5

For your task, you don't need pipelines or sed. It can all be done much more efficiently using builtin bash commands like this:

NewMsg=${MSG//;/$'\n'}

${MSG//;/$'\n'} is an example of pattern substitution. It replaces every occurrence of ; with a newline character. The result is saved in the shell variable NewMsg.

As an example:

$ Msg='1;2;3'
$ NewMsg=${Msg//;/$'\n'}
$ echo "$NewMsg"
1
2
3

Notes:

  1. It is best practice to use lower-case or mixed-case shell variables. The system uses all caps for its variables and you don't want to accidentally overwrite one of them.

  2. Unless you explicitly want word splitting and pathname expansion always put your shell variables in double-quotes. Thus, when temped to use echo $MSG, use instead echo "$MSG".

  3. Also, unless you know what characters are going to be in the string that you are echoing, echo has problems and it is safer and more portable to use printf '%s\n' "$MSG". For more details, see Stéphane Chazelas' very informative discussion of echo vs printf.

  4. Be aware that if you do use command substitution, $(...), the shell will remove all trailing newlines. While this is usually helpful, there are times when the change is unwanted.

John1024
  • 74,655
  • @StéphaneChazelas Good point and your linked answer includes an impressive lot of information. Thanks. The answer is updated to mention printf and include that link. – John1024 Jun 14 '19 at 18:51
  • While removing one trailing newline is usually helpful, removing the other ones is almost always unwanted. – Stéphane Chazelas Jun 14 '19 at 21:18
2

Simply assign it to the variable like this:

MSG2=$(echo $MSG | sed -e $'s/;/\\n/g')
jjj
  • 111
  • 1
    Or use sed with y/;/\n/ which does not require $'...' and which is portable (or more simply tr ';' '\n' instead of sed). Also remember to quote $MSG or the shell may expand glob patterns in its value. – Kusalananda Jun 14 '19 at 06:56
  • sed -e $'s/;/\\n/g' is sed -e 's/;/\n/g' so is a non-portable variant of the OP's portable (in bash) sed -e $'s/;/\\\n/g' – Stéphane Chazelas Jun 14 '19 at 07:18