Remi.b Remi.b - 3 months ago 11
Bash Question

Store output of sed with command substitution in it into a variable

Consider a string

Message="Hello WoRld"


I would like to substitute the upper case
R
by the lower case
r


echo "$Message" > file.txt
NewMessage=$(sed 's/R/r/' file.txt)


works fine! The following would work as well

NewMessage=$(echo ${Message} | sed 's/R/r/')


But my first reflex was to use command substitution

NewMessage=$(sed 's/R/r/' <("$Message"))


but it does not work. Why doesn't it work?

Answer

your cmd-sub version was missing the leading M?

But you want

NewMessage=$(sed 's/R/r/' <(echo "$Message"))

OR your shell may support

NewMessage=$(sed 's/R/r/' <<< "$Message")

edit

and the simplest, most widely supported solution would be much simpler

NewMessage=$(echo "$Message" | sed 's/R/r/') 

If you need absolute stone-age compatibility to Bourne Shell (true /bin/sh) then you'll have to forego the nice $(..cmdSub) syntax and use back-quotes for command-substitution:

NewMessage=`echo "$Message" | sed 's/R/r/'` 

IHTH

Comments