1

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
s/a/X/
s/X/&a&/

While shell variables are not expanded

$cat script.sed
s/$varin/$varout/
a/$varout/&$varin&/

$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

5

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

$ cat script.sed
s/$varin/$varout/
s/$varout/&$varin&/

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
s/a/X/
s/X/&a&/

The sed command using a process substitution:

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

Heredoc to the rescue:

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

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 .