Search code examples
kshstring-substitutionexpression-evaluation

How to expand macros in strings read from a file in a ksh script?


I want to read a list of file names stored in a file, and the top level directory is a macro, since this is for a script that may be run in several environments. For example, there is a file file_list.txt holding the following fully qualified file paths:

$TOP_DIR/subdir_a/subdir_b/file_1
$TOP_DIR/subdir_x/subdir_y/subdir_z/file_2 

In my script, I want to tar the files, but in order to do that, tar must know the actual path. How can I get the string containing the file path to expand the macro to get the actual path? In the code below the string value echoed is exactly as in the file above. I tried using actual_file_path=`eval $file_path` and while eval does evaluate the macro, it returns a status, not the evaluated path.

for file_path in `cat $input_file_list`
do
    echo "$file_path"
done

Solution

  • With the tag ksh I think you do not have the utility envsubst.
    When the number of variables in $input_file_list is very limited, you can substitute vars with awk :

    awk -v top_dir="${TOP_DIR}" '{ sub(/$TOP_DIR/, top_dir); print}' "${input_file_list}"