I have a single input file that needs to be replicated multiple times with a little change in every file i.e every 30th line in every file is to change.

For e.g.

My main text file name is D0.txt which I need to replicate multiple numbers time. and in that line 30 is "variable D1 equal 0.0 "

Now for the first time when I replicate this file

I would like to change that string to " variable D1 equal 1 "

and then save the file as D1.txt.

Similarly, I would like to create suppose 5 files then I would like to loop it 100 times.

so files are saved in a folder as



D2.txt and so on with each of their line 30 as "Diameter = $n" sample text file format is attached below. and desired format of files in folder.

enter image description here enter image description here

1 Answer 1


In bash you can do

for i in {1..5}; do
 cp D0.txt D$i.txt;
 sed -i "30s/.*/variable D1 equal $i/" D$i.txt;

Here {1..5} specify the range of the loop and during each iteration we are

Making copy of file with new Name. Using sed command to replace the text on line 30. where -i specify in-place ,30 specify line number, s specify to serch the given text in our case it is .* which states any text on line 30 and we want to replace that text with variable D1 equal $i to the file D$i.txt.

  • Thanks, @Vaibhav.c Solution provided works perfectly. It would save me a lot of time. Thanks again for taking out time to solve it.
    – Yash54
    Mar 24, 2022 at 10:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .