How to expand shell variables in a text file?

前端 未结 10 1443
夕颜
夕颜 2021-02-04 02:05

Consider a ASCII text file (lets say it contains code of a non-shell scripting language):

Text_File.msh:

spool on to \'$LOG_FILE_PATH/lo         


        
相关标签:
10条回答
  • 2021-02-04 02:45

    This solution allows you to keep the same formatting in the ouput file

    Copy and paste the following lines in your script

    cat $1 | while read line
    do
      eval $line
      echo $line
      eval echo $line
    done | uniq | grep -v '\$'
    

    this will read the file passed as argument line by line, and then process to try and print each line twice: - once without substitution - once with substitution of the variables. then remove the duplicate lines then remove the lines containing visible variables ($)

    0 讨论(0)
  • 2021-02-04 02:45

    Create an ascii file test.txt with the following content:

    Try to replace this ${myTestVariable1} 
    bla bla
    ....
    

    Now create a file “sub.sed” containing variable names, eg

    's,${myTestVariable1},'"${myTestVariable1}"',g;
    s,${myTestVariable2},'"${myTestVariable2}"',g;
    s,${myTestVariable3},'"${myTestVariable3}"',g;
    s,${myTestVariable4},'"${myTestVariable4}"',g'
    

    Open a terminal move to the folder containing test.txt and sub.sed.
    Define the value of the varible to be replaced

    myTestVariable1=SomeNewText
    

    Now call sed to replace that variable

    sed "$(eval echo $(cat sub.sed))" test.txt > test2.txt
    

    The output will be

    $cat test2.txt
    
    Try to replace this SomeNewText 
    bla bla
    ....
    
    0 讨论(0)
  • 2021-02-04 02:46

    Yes eval should be used carefully, but it provided me this simple oneliner for my problem. Below is an example using your filename:

    eval "echo \"$(<Text_File.msh)\""
    

    I use printf instead of echo for my own purposes, but that should do the trick. Thank you abyss.7 providing the link that solve my problem. Hope it helps.

    0 讨论(0)
  • 2021-02-04 02:47

    If the variables you want to translate are known and limited in number, you can always do the translation yourself:

    sed "s/\$LOG_FILE_PATH/$LOG_FILE_PATH/g" input > output
    

    And also assuming the variable itself is already known

    0 讨论(0)
提交回复
热议问题