After running this code

rm -f myfile myfile-individual
echo "Greetings, foobar!" > myfile
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!

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.
  • Thanks. I found that 's:foobar:'$MYSTRING':' will also work, but the double quotes make the code more legible. Quick sequel: is it possible for sed to substitute in-place (without saving into a new file)? – Calaf Apr 5 '12 at 17:29
  • Yes, look at the -i option in sed. – Arcege Apr 5 '12 at 17:58
  • Instead of sed -i you should look into ed as well. sed -i breaks links and is not very portable but if you don't have to worry about either, then it may be fine. – jw013 Apr 5 '12 at 18:35
  • @Calaf: .. regarding what you said about 's:foobar:'$MYSTRING':' will also work.. It won't work if $MYSTRING contains a sequence of whitespace; which the shell will collapse into a single space... However 's:foobar:'"$MYSTRING"':' will work in that case. – Peter.O Apr 6 '12 at 6:59
sed -i 's|foobar|$MYSTRING' myfile-individual 

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.