-1

Before to write, of course I read many other similar cases. Example I used #!/bin/bash instead of #!/bin/sh I have a very simple script that reads lines from a template file and wants to replace some keywords with real data. Example the string <NAME> will be replaced with a real name. In the example I want to replace it with the word Giuseppe. I tried 2 solutions but they don't work.

#!/bin/bash
#read the template and change variable information
while read LINE
do
 sed 'LINE/<NAME>/Giuseppe' #error: sed: -e expression #1, char 2: extra characters after command
 ${LINE/<NAME>/Giuseppe}    #error: WORD(*) command not found
done < template_mail.txt

(*) WORD is the first word found in the line

I am sorry if the question is too basic, but I cannot see the error and the error message is not helping.

EDIT1:

The input file should not be changed, i want to use it for every mail. Every time i read it, i will change with a different name according to the receiver.

EDIT2:

Thanks your answers i am closer to the solution. My example was a simplified case, but i want to change also other data. I want to do multiple substitutions to the same string, but BASH allows me only to make one substitution. In all programming languages i used, i was able to substitute from a string, but BASH makes this very difficult for me. The following lines don't work:

CUSTOM_MAIL=$(sed 's/<NAME>/Giuseppe/' template_mail.txt) # from file it's ok
CUSTOM_MAIL=$(sed 's/<VALUE>/30/' CUSTOM_MAIL) # from variable doesn't work

I want to modify CUSTOM_MAIL a few times in order to include a few real informations.

CUSTOM_MAIL=$(sed 's/<VALUE1>/value1/' template_mail.txt)
${CUSTOM_MAIL/'<VALUE2>'/'value2'}
${CUSTOM_MAIL/'<VALUE3>'/'value3'}
${CUSTOM_MAIL/'<VALUE4>'/'value4'}

What's the way?

fresko
  • 1,890
  • 2
  • 24
  • 25

1 Answers1

2

No need to do the loop manually. sed command itself runs the expression on each line of provided file:

sed 's/<NAME>/Giuseppe/' template_mail.txt > output_file.txt

You might need g modifier if there are more appearances of the <NAME> string on one line: s/<NAME>/Giuseppe/g

buff
  • 2,063
  • 10
  • 16
  • Thanks. What if instead to put the output in output_file.txt i would like to have it in a variable? – fresko Jul 27 '15 at 10:16
  • 1
    Then direct it to a variable instead. `variable=$(sed 's//Giuseppe/' template_mail.txt)`. Notice that you need to [properly quote](http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable) `"$variable"` in double quotes to preserve newlines when interpolating the value. – tripleee Jul 27 '15 at 10:29
  • Thanks, i was using the $LINE that's why i couldn't. I am doing this script exceptionally, i usually do other things that's why i do so basic mistakes. – fresko Jul 27 '15 at 10:45