Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use sed in bash to replace string with heredoc

Tags:

bash

sed

In a bash script I need to replace a placeholder string in a file with some heredoc. How do I do that?

e.g. sed -i 's/PLACEHOLDER_TEXT/$HEREDOC/g' > file.txt where

<<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC
like image 763
Dave Avatar asked Dec 14 '25 06:12

Dave


2 Answers

pass trhough a temporary file and avoid a substitute due to behavior of replace pattern special char that can occur (like &,\x)

so

cat > /tmp/HereFile <<HEREDOC
Some multiple
lines of
text to replace PLACEHOLDER_TEXT
HEREDOC

sed '/PLACEHOLDER_TEXT/ {
   r /tmp/HereFile
   d
   }' YourFile
rm /tmp/HereFile 
like image 176
NeronLeVelu Avatar answered Dec 16 '25 23:12

NeronLeVelu


Just flatten it out (you can change the # if that may appear in your data) and put the newlines back in afterward like:

sed "s/PLACEHOLDER_TEXT/$(echo "$HEREDOC"|tr "\n" "#")/g;s/#/\n/g" file.txt

To build the $HEREDOC variable:

$> export HEREDOC=$(cat<<EOF

    > what is going 
    > on with 
    > this 
    > thing
    > EOF
    > )

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!