0

Is there a way within bash to replace placeholders in a text file with the contents of variables?

For example, I want to send an email notification out that looks like:

Dear Foo, 

Alert: <Alert error text 1> 

<Alert error text 2>

blah blah blah blah blah blah

I saw a related article (How to replace ${} placeholders in a text file?) but in the example, it adds static content. The catch is that "alert error text 1" and "alert error text 2" are always changing. I'm not aware of a way to use SED/AWK to replace the markers with dynamic content.

Is this possible?

Community
  • 1
  • 1
Mike B
  • 151
  • 1
  • 10

5 Answers5

3
e1=dog
e2=bird
sed "
s/<Alert error text 1>/$e1/
s/<Alert error text 2>/$e2/
"
Zombo
  • 1
  • 62
  • 391
  • 407
  • I tried this but it doesn't seem to be working - if the alert error text has simple alpha-numeric output, it works fine. But in some-cases, it has additional special characters and when that's present, it appears to be blank in the final output. Is there a way to help sed cope with variable content that has special characters? – Mike B Apr 28 '13 at 02:50
2

This seems like a job for printf:

template="Dear Foo, 

Alert: %s 

%s

%s"

# Prior to bash 4
instance=$(printf "$template" "$AlertText1" "$AlertText2" "$Body")

# Bash 4+
printf -v instance "$template" "$AlertText1" "$AlertText2" "$Body"
chepner
  • 497,756
  • 71
  • 530
  • 681
1
 sed -e 's/<Alert error text 1>/'$e1'/' -e 's/<Alert error text 2>/'$e2'/' file.txt

where $e1 and $e2 are the variables.

Sidharth C. Nadhan
  • 2,191
  • 2
  • 17
  • 16
  • I tried this but it doesn't seem to be working - if the alert error text has simple alpha-numeric output, it works fine. But in some-cases, it has additional special characters and when that's present, it appears to be blank in the final output. Is there a way to help sed cope with variable content that has special characters? – Mike B Apr 28 '13 at 02:51
1

Did you see the old solution posted here, that can handle command substitution?

https://stackoverflow.com/a/17030953/1322463

eval "cat <<EOF $(<template.txt) EOF " 2> /dev/null

so template could have stuff like: Hello $USER, Today is $(date)

With output of: Hello plockc, Today is Sun Jun 26 13:16:28 PDT 2016

Just make sure you control the template otherwise anything that gets run is run as your user.

Community
  • 1
  • 1
plockc
  • 4,241
  • 3
  • 18
  • 9
0

This might work for you:

template () {
cat <<!
Dear $1,

I'm fine, hope you are too.

Love $2
!
}

template foo bar
potong
  • 55,640
  • 6
  • 51
  • 83