Extract a number from a line in a file and sed in another copied file

Dear all,
I am trying to extract a number from a line in one file (task 1), duplicate another file (task 2) and replace all instances of the strings 300, in duplicated with the extracted number (task 3). Here is what I have tried so far:

for ((k=1;k<4;k++)); do

 temp=`sed -n "${k}p" temperatures`; #Task 1
 
 cp nvt.mdp nvt_$k.mdp; #Task 2

 sed 's/300/$temp/g' < nvt_$k.mdp > $k_nvt.mdp; #Task 3

done

temperatures file:

275
277
279
281

nvt.mdp file

...
tau_t           = 0.1   0.1     ; time constant, in ps
ref_t           = 300   300     ; reference temperature, one for each group, in K
...

The result is that I get copies of nvt_1.mdp to nvt_3.mdp correctly, however, I obtain only one copy from task 3 and it is not even named correctly ie. 1_nvt.mdp is only .mdp.

In addition, since the sed command extracts a string from the line, it also extracts with it the line-break "character", changing the formatting of .mdp file.

I realized that if I were to convert the extracted number into an integer it should in theory work to prevent the format change of task 3 files. Though typset -i before Task 1 command gives the error:

")syntax error: invalid arithmetic operator (error token is "

If anyone could help with the proper implementation of task 3 such that formatting of $k_nvt.mdp is not changed and the proper number of copies are generated, I would be very grateful.

Cordially,
Ali

Please try this within the loop and check:

temp=`sed "${k}s/^[^0-9]*\([0-9]*\).*$/\1/g" temperatures`; #Task 1

cp nvt.mdp nvt_$k.mdp; #Task 2

sed 's/300/$temp/g' < nvt_$k.mdp > ${k}_nvt.mdp; #Task 3

This corrects the error of naming the new files in Task 3. Thank you.

However, the new files do not contain anything and running the script returns the following error:

sed: -e expression #1, char 9: unterminated `s' command