1

I have a file template that will be used by a shell script to generate other files and just change a fill information inside this file template using variables.

content of file template.example.log:

server name: $HOSTNAME
current user: $USER

I try different ways to do this works.

content of file log.sh:

1) do not work, the output file some_log_1.log is the same as template.example.log and the variables was not changed.

FILE_TEMPLATE="`cat template.example.log`"
cat > some_log_1.log <<EOF
$FILE_TEMPLATE
EOF

2) do not work with echo command too, happen the same as above.

echo $FILE_TEMPLATE > some_log_1.log

but if I do this, it works!

cat > some_log_1.log <<EOF
    server name: $HOSTNAME
    current user: $USER
EOF

the output is right!

server name: ubuntu-server
current user: leafar

but I do not want the script run in this way. I want to read the content of a text file and cat it into another text file and fill the variables.

HOW CAN I DO THAT? THANKS. Ps: sorry about my weak english

1 Answers1

3

One option is to use sed to edit the files. This lets you limit what variables get filled in.

This will fill in template.txt and output it to filled.txt:

sed -e "s/\$HOSTNAME/$HOSTNAME/" -e "s/\$USER/$USER/" template.txt > filled.txt

template.txt:

server name: $HOSTNAME
current user: $USER

filled.txt:

server name: ubuntu-server
current user: leafar
Brian
  • 3,476
  • 18
  • 16