How to expand shell variables in a text file? How to expand shell variables in a text file? bash bash

How to expand shell variables in a text file?


This question has been asked in another thread, and this is the best answer IMO:

export LOG_FILE_PATH=/expanded/path/of/the/log/file/../logfile.logcat Text_File.msh | envsubst > Text_File_expanded.msh

if on Mac, install gettext first: brew install gettext

see:Forcing bash to expand variables in a string loaded from a file


This solution is not elegant, but it works. Create a script call shell_expansion.sh:

echo 'cat <<END_OF_TEXT' >  temp.shcat "$1"                 >> temp.shecho 'END_OF_TEXT'       >> temp.shbash temp.sh >> "$2"rm temp.sh

You can then invoke this script as followed:

bash shell_expansion.sh Text_File.msh Text_File_expanded.msh


If a Perl solution is ok for you:

Sample file:

$ cat file.shspool on to '$HOME/logfile.log';login 'username' 'password';

Solution:

$ perl -pe 's/\$(\w+)/$ENV{$1}/g' file.shspool on to '/home/user/logfile.log';login 'username' 'password';