Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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!
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.
share|improve this answer
    
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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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