0

I want to modify a specific line in my code

program main
...
seed=k+rank
...
end 

and increment k by intervals of m(=96, in my example). So my implementation of the same in shell should look something like

for k in {1..961..96};
do sed -i "s/{seed=k+rank}/{seed=k+96+rank}/g" main.f90;
#run the program
sleep 15m;
done

but this changes the string seed=1+rank to seed=1+96+rank instead of writing 97+rank and would not proceed on the next iteration.

(Bash script using sed with variables in a for loop? is what I could find)

I've searched for the use of sed through a bash loop but couldn't find or figure out the command specific to my purpose.

ferro11001
  • 13
  • 4

2 Answers2

0

You shouldn't do the replacement in place. After the first iteration, the file won't have k in it any more, since k will have been replace. You should read from a template file and write to a different file that will be executed.

You need to use $k in the replacement string to get the value of the shell variable.

And you shouldn't have {} in the sed pattern or replacement.

for k in {1..961..96};
    do sed "s/seed=k+rank/seed=$k+rank/g" template.f90 > main.f90;
    #run the program
    sleep 15m;
done

Although I wonder why you don't just change the program so that it gets the value of k from a command-line argument or standard input. Then you won't have to modify the program for each run.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • sorry but I don't get why would substituting k with $k work, I also need to increment it with 96; so I tried doing ``` sed "s/seed=$k+rank/seed=$(($k+96))+rank/g" template.f90 > main.f90 ``` which yielded in a syntax error – ferro11001 Jul 08 '22 at 21:06
  • although I do agree getting an argument from command line would be the easier approach I now also want to figure out how to use sed correctly in this context – ferro11001 Jul 08 '22 at 21:11
  • `{1..961..96}` increments `$k` by 96 each time through the loop. – Barmar Jul 08 '22 at 21:23
  • So the first time it will be `seed=1+rank`. Then next time it will be `seed=97+rank`. And so on. – Barmar Jul 08 '22 at 21:24
0

ok, this worked:

for k in {1..961..96}; 
do m=$k; n=$(($k+96)); 
sed -i "s/seed=$m+rank/seed=$n+rank/g" main.f90 ;
#run main program
sleep 15m 
done
ferro11001
  • 13
  • 4