Variable substitution into a sed script

After running this code

#!/bin/bash
rm -f myfile myfile-individual
echo "Greetings, foobar!" > myfile
MYSTRING="Jack"
cat myfile | sed 's:foobar:$MYSTRING:' > myfile-individual

we end up with

Greetings, $MYSTRING!

in myfile-individual.

What should be the (sed/bash) script for the output to be instead

Greetings, Jack!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Change the single quotes to double quotes. And drop the cat (UUoC):

sed "s:foobar:$MYSTRING:" myfile > myfile-individual

From the manpage for bash:

   Enclosing characters in single quotes preserves the  literal  value  of
   each character within the quotes.  A single quote may not occur between
   single quotes, even when preceded by a backslash.

   Enclosing characters in double quotes preserves the  literal  value  of
   all  characters  within the quotes, with the exception of $, `, \, and,
   when history expansion is enabled, !.  The characters $  and  `  retain
   their  special meaning within double quotes.  The backslash retains its
   special meaning only when followed by one of the following  characters:
   $,  `,  ", \, or <newline>.  A double quote may be quoted within double
   quotes by preceding it with a backslash.  If enabled, history expansion
   will  be  performed  unless an !  appearing in double quotes is escaped
   using a backslash.  The backslash preceding the !  is not removed.

Solution 2

sed -i 's|foobar|$MYSTRING' myfile-individual 

This will do the substitution as well as write it in file

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply