Search code examples
bashreplacesedawktextutils

Fill placeholders in file in single pass


I have a skeleton text file with placeholder strings:

blah blah blah
blah $PLACEHOLDER_1$
blah
$PLACEHOLDER_2$

and so on. Specific "form" of placeholders does not matter -- I may change them to whatever most comfortable for specific implementation.

I have a bash script where I know values for placeholders, and I need to generate a new file, with placeholders replaced with values.

#! /bin/sh
PLACEHOLDER_1 = 'string 1'
PLACEHOLDER_2 = 'multiline 
string 
2'
# TODO: Generate file output.txt from file output.template 
#       using placeholders above.

I may do this in multiple passes with sed, but it is not fun. I do not want to use Perl. I want to use textutils and bash itself only.

What is the best way to do what I want in a single pass?


Solution

  • You can still use sed to do the replace in a single pass. You just need to specify all the replacements in one command.

    eg.

    sed -i 's/PLACEHOLDER_1/string 1/g;s/PLACEHOLDER_2/string 2/g' <file>