F
F
foboss2014-07-14 13:45:39
bash
foboss, 2014-07-14 13:45:39

How to substitute in a string taken from a file the value of a variable set in the script in a bash script?

There is an example.txt file, which contains lines like:

# Comment 1
$VAR1/teststring1
# Comment 2
$VAR2/teststring2

There is a bash script:
#!/bin/bash

VAR1="hello"
VAR2="world"

STRING=`awk '!/^\ *#/&&(length > 0), ORS=" "' example.txt`

echo $STRING

Of course, when outputting, the variables from the file are printed as they are:
$VAR1/teststring1 $VAR2/teststring2
How can I force the script to substitute the values ​​above into these variables? Is there a simple and obvious way? Fencing a separate regexp replacement for this does not seem reasonable.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
xotkot, 2014-07-14
@foboss

replace the last line with:
eval "echo $STRING"

S
Sergey Petrikov, 2014-07-14
@RicoX

If vlob then the dumbest option that comes to mind is to replace the last line with

echo $STRING | sed -e 's/\$VAR1/'$VAR1'/g' -e 's/\$VAR2/'$VAR2'/g'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question