Directly on the command line, this works:

$sed "s/a/X/;s/X/&a&/" file

and so does using shell variables:

$varin=a ; varout=X ; sed "s/$varin/$varout/;s/$varout/&$varin&/" file

However using an external script file

$sed -f script.sed file

Only the "hardcoded" approach works

$cat script.sed

While shell variables are not expanded

$cat script.sed

$varin=a ; varout=X ; sed -f script.sed file
#-> variables in script.sed not interpreted; output unchanged

How to achieve the interpretation of shell variables within an external sed script file?

I quite understand that sed itself cannot interpret the shell variables, but how could I preprocess the script (in a save manner) to once run it through bash for resolving variables? Maybe one could import them to sed with a command at the beginning?

The following approaches were not fruitful (using bash):

  • using export varin=a ; export varout=X
  • via sed -e $(cat sed.script) file: works for single-line script, fails on multi-line ones, even with comment as first line
  • sed -f <(cat script.sed) file
  • eval sed -f script.sed file

2 Answers 2


You could use envsubst to replace the variables in your script with the intended values before running sed.

$ cat script.sed

Replacing the strings $varin or ${varin} and $varout or ${varout} in script.sed with their variables values:

$ varin='a' varout='X' envsubst '$varin $varout' <script.sed

The sed command using a process substitution:

sed -f <(varin='a' varout='X' envsubst '$varin $varout' <script.sed) file
  • Nice program, any dangers know regarding e.g. special characters?
    – FelixJN
    Mar 16, 2021 at 8:23

Heredoc to the rescue:

varin=a; varout=X
sed -f - <<_CODE_    file

But mind you, this approach is fraught with errors/incorrect results , if the shell vars being parachuted inside w/o proper sanitization. Take for example, what would happen if varout contained the character & or / etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .