LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Variables in text file, how to get their values when printing out the text? (https://www.linuxquestions.org/questions/linux-general-1/variables-in-text-file-how-to-get-their-values-when-printing-out-the-text-801733/)

idaham 04-13-2010 08:13 AM

Variables in text file, how to get their values when printing out the text?
 
Hi!
I'm doing some bash-scripting and want to be able to print some text (just plain text) files into the new bash-scripts, created within a loop. Here's a short example of what I do:

Code:

############### main bash script ##################
#!/bin/bash

##Filename
variable1=10

for ((j=0;j<=40;j+=1))
do
  ## Create another bash-script
  echo "#!/bin/bash" >> bash_script_$j
  ... some stuff...
  cat file1.txt >> bash_script_$j
  ... some more stuff...
done

where the text file (file1.txt) I want to print in the the new bash script looks something like:
Code:

############### file1.txt ##################
...some stuff...
logsave log some_program($variable1)
mv output_$j folder_$j/
... some more stuff...

I.e, the text file contains variables such as "$j", "$variable1" etc that are undefined. Doing the above works for creating new bash scripts (bash_script_1 - bash_script_40) but the variables are not determined. I would like, if possible, to somehow print the text in file1.txt into the new bash-scripts with the variables determined, i.e:
Code:

############### bash_script_1 ##################
...some stuff...
logsave log some_program(10)
mv output_1 folder_1/
... some more stuff...

The text files I read are quite extensive so I would really prefer not having to paste them into the FOR-loop directly. Does anyone have any suggestions? Thanks!
Ida

catkin 04-13-2010 08:36 AM

Presuming you call the scripts created on the fly, could you pass the variable values on the command line?
Code:

#!/bin/bash

##Filename
variable1=10

for ((j=0;j<=40;j+=1))
do
  ## Create another bash-script
  echo "#!/bin/bash" >> bash_script_$j
  echo 'j=$1' >> bash_script_$j
  ... some stuff...
  cat file1.txt >> bash_script_$j
  ... some more stuff...
  bash_script_$j $j
done

Alternatively, they could get the value of $j from their own name
Code:

j=${0##*_}

idaham 04-14-2010 03:28 AM

Hi!

I was able so solve the problem using the "sed" command:

Code:

sed -e s#'$variable1'#$variable1#g -e s#'$j'#$j#g file1.txt >> bash_script_$j
/Ida


All times are GMT -5. The time now is 10:08 AM.