Argumanez Argumanez - 1 year ago 54
Linux Question

Linux bash scritp to replace string inside file and executing a program multple times

I have a program that needs two files as input and takes 10 minutes each time I execute it. I need to execute this program 500 times, but before each execution I need to change a part of a word in each of the two input files.

For example, I have a directory with the following files: a_1, a_2, ..., a_499, a_500, input1.dat and input2.dat. I need a script in bash in order that, when I execute this script:

1) The string "a_1" (which is the name of my first file in my directory) is replaced by the string "a_2" (second file in directory) in both input files: input1.dat and input2.dat.

2) My program is executed as:

myprogram -i input1.dat

(the reason why it only appears input1.dat is because it calls input2.dat inside)

3) When the executions ends, the string "a_2" is replaced by "a_3" in both input files.

4) My program is executed again

I need to do this for all my files in the directory (until "a_499" is replaced by "a_500" and the program is executed for the last time), without changing the names of both input files

I am new in bash, so this is out of my reach, but if someone could help me it would save me a lot of time.

Answer Source

I assume that you will want to run the fist time with a_1, even though that is not clear from your description. The script below should do the trick and should be easily understandable.

cp input1.dat orig1.dat
cp input2.dat orig2.dat
for f in a_* ; do
    sed "s/a_1/$f/g" orig1.dat > input1.dat
    sed "s/a_1/$f/g" orig2.dat > input2.dat
    myprogram -i input1.dat
done
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download