almighty_dollar
almighty_dollar

Reputation: 67

Replacing a line with a new one containing a variable

Here's my code:

for num in {0001..1000}; do

   cd ${num}_1000_solar
   sed -i '827s/.*/ if(BigUni==1) fp910=fopen("biguni_${num}.dat","w");/' binary.c
   gcc singl.c binary.c -lm
   cd ..
done

sed command writes '{num}' into a file instead of putting there an appropriate value from the loop. How can I replace a line with a string + some variable?

Cheers!

Upvotes: 0

Views: 50

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

If ${num} is to be interpreted by the shell, it must be in double quotes (or outside quotes), not single quotes.

for num in {0001..1000}
do
    (
    cd ${num}_1000_solar
    sed -i '827s/.*/ if (BigUni==1) fp910=fopen("biguni_'"${num}"'.dat","w");/' binary.c
    gcc singl.c binary.c -lm
    )
done

Having 1000 programs where you change the file name in the source code and recompile (to a.out each time) is an abuse of C. You should pass the file name in as an argument to the program. In other words, the exercise is only necessary because the setup is deeply flawed.

Also, as a general rule, I avoid cd subdir followed later by cd .. in scripts when it's feasible. By running a sub-shell (the ( and ) in the revised script), the calling shell process is unaffected by any changes of directory. Ultimately, it's more reliable.

Upvotes: 2

Related Questions