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!
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!
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:
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.
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"
.
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
.
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.
Simply assign it to the variable like this:
MSG2=$(echo $MSG | sed -e $'s/;/\\n/g')
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
printf
and include that link. – John1024 Jun 14 '19 at 18:51