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.
CodePudding user response:
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.
CodePudding user response:
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