Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute shell variables in complex text files

I have several text files in which I have introduced shell variables ($VAR1 or $VAR2 for instance).

I would like to take those files (one by one) and save them in new files where all variables would have been replaced.

To do this, I used the following shell script (found on StackOverflow):

while read line do     eval echo "$line" >> destination.txt done < "source.txt" 

This works very well on very basic files.

But on more complex files, the "eval" command does too much:

  • Lines starting with "#" are skipped

  • XML files parsing results in tons of errors

Is there a better way to do it? (in shell script... I know this is easily done with Ant for instance)

Kind regards

like image 379
Ben Avatar asked Jan 04 '13 10:01

Ben


People also ask

How do I change environment variables in shell?

You can set your own variables at the command line per session, or make them permanent by placing them into the ~/. bashrc file, ~/. profile , or whichever startup file you use for your default shell. On the command line, enter your environment variable and its value as you did earlier when changing the PATH variable.

What is Envsubst command?

The envsubst command searches the input for pattern $VARIABLE or ${VARIABLE}. Then, it replaces the pattern with the value of the corresponding bash variable. In contrast, a pattern that does not refer to any variable is replaced by an empty string. Moreover, envsubst recognizes only exported variables.

What is $$ in shell script?

$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing. 8.


1 Answers

Looking, it turns out on my system there is an envsubst command which is part of the gettext-base package.

So, this makes it easy:

envsubst < "source.txt" > "destination.txt" 

Note if you want to use the same file for both, you'll have to use something like moreutil's sponge, as suggested by Johnny Utahh: envsubst < "source.txt" | sponge "source.txt". (Because the shell redirect will otherwise empty the file before its read.)

like image 112
derobert Avatar answered Oct 17 '22 23:10

derobert