0

I have a file with cpp code named model_c2.cpp. One of the line in code is:

double n=0.0;

I want to use bash and sed to loop it through from 1.0 to 50.0. I tried the following loop but it isn't working. What I am doing wrong?

#!/bin/bash

for i in $(seq 1 50);
do
    sed -i -e 's/n=*/n=$i.0/g' $model_c2.cpp    
done
1
  • What are you trying? It seems like a better idea to make you program read it as an input parameter. You don't want to work with 50 different version of an executable... Commented Nov 12, 2013 at 21:08

2 Answers 2

4
  • please use double quotes to expand shell variables
  • also you need regex, .*, not glob *

    sed -i -e "s/n=.*/n=$i.0;/g" $model_c2.cpp  
    
Sign up to request clarification or add additional context in comments.

Comments

0

Do you want to run or compile the program with n assigned to each of those values in turn? Are you hoping to save out the file with unique names?

Your script will only "keep" the last value that you have substituted at this point, so it doesn't seem like you want it in a loop unless you save it with different names.

Also why do you have $model instead of just model? Is that variable defined elsewhere...?

If you are trying to save 50 different cpp files with different names, then put $i in your destination file name:

for i in $(seq 1 50);
do 
    sed -e "s/double n=.*/double n=$i.0;/" model_c2.cpp > model_$i_c2.cpp
done

This will make 50 files called model_1_c2.cpp ... model_50_c2.cpp

I think the searching for every n= is a bit dangerous, as it will replace ANY line with any other variable ending in n. I've added the double back in as a bit of an assurance against this...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.