Search code examples
pythonbashfilecopy-paste

Making several copies of a file replacing some word with bash or python


I have a some file my_file. I have a list (of length n) of words and I want to make n copies of the file with elements from the list appended at the end of the file and also changing all words 'x' met in my_file with the corresponding entity from the list.

For example : if my file is

----my_file.txt---
This is my x file
------------------

and my list is {a,b,c} I want three files : my_filea.txt, my_fileb.txt and my_filec.txt and in each of them the letter x changed to a,b,c, accordingly.

It is convenient for me to do this with bash or python. Any suggestions?


Solution

  • This is the python script to do that .

    import re
    data=open("myfile.txt","r").read()
    listinput=['a','b','c']
    for i in listinput:
        changed_data=re.sub("x file",i+" file",data)
        fp2=open("myfile"+i+".txt","w")
        fp2.write(changed_data)
        fp2.close()