I set a variable in a shell script I then call a sed script and in the sed script I use the variable That does not seem to work and I needed help on how to achieve that

  1. Following works at the command line

sed -e "s/text/$VAR" testfile

  1. Following does not work


export VAR=somevar
sed -f sedfile testfile


This is a test file



Also tried



This is a $VAR file

Expected output

This is a somevar file

2 Answers 2


The soft quotes " on the command line version of your example allow for shell expansion of the variable by your shell, before sed executes the sed instructions.

The sedfile is not a shell script, it is a sed script interpreted by sed, so no shell expansion of the variable can take place. That is simply not going to work AFAIK.


you may wish to generate sedfile using here document syntax

cat <<foobar > sedfile
  • foobar must be used at the start of the line
  • foobar can be any string, just use the same string in <<foobar

then do the seding

sed -f sedfile testfile

I expect your sedfile is a bit complex, for one or two substitutions it might not be worth using it.

  • This will not be possible in our environment but its a good workaround. Looks like there is no way to perform the task I requested but I will keep checking. Oct 17, 2014 at 5:21

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.