-5

I'm trying to replace text between 2 strings using Python or sed. I read all what I found on Stack Overflow, but my skills don't seems to be enough to adapt what I found to my problem.

I have 2 files :

  1. Courses.txt:

    Course = bla
    Room number(1)
    url http://foobar
    
  2. dst.txt:

    //Start
    
    Course = foo
    Room Number(2)
    url http://bar
    
    //End
    

My goal is to replace what is between //Start and //End in dst.txt with what is read in Courses.txt.

I looked here :

but was not able to use them.

Community
  • 1
  • 1
Processor
  • 304
  • 1
  • 3
  • 14

3 Answers3

2
sed '\#^//Start#,\#^//End#{
   \#^//End# !d
   r Courses.txt
   }' dst.txt

Explanation:

  • for every thing between start and end (\#//^Start#,\#//^End#) using a different delimiter \# than default /, execute sub action inside {}
    • for all line except end (\#^//end# !), delete the line (d) [and cycle to next line]
    • [if not the case, so contain end], replace by (read) content of file Course.txt
NeronLeVelu
  • 9,908
  • 1
  • 23
  • 43
  • Hi NeronLeVelu, First of all thanks for your answer. Then I just copy/past your answer and I just had an echo of what there is in dst.txt, but nothing replaced. – Processor Oct 27 '15 at 11:00
  • The echo was due to an error of mine, but unfortunately for me, once corrected, the code did nothing. – Processor Oct 27 '15 at 11:18
2
 import re
 with open('Courses.txt', 'r') as f1, open('dst.txt', 'r') as f2:
        text = f1.read()
        text2 = f2.read()
        ntext = re.sub(r'(//Start.*?\n+)(.*)(//End)',r'\1' + text + r'\3',text2, flags=re.M|re.DOTALL)

    with open('dst.txt', 'w') as fout:
        fout.write(ntext)
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
0

i know this late but here is my solution: note this will overwrite the content of original file so make sure to back it up

f = open("test.txt","r")
lines = f.readlines()
f.close()
f = open("test.txt","w")
start=False
for line in lines:
    if line.strip() == "starting string":
        f.write(line)
        start=True
    elif line.strip() == "ending string":
        f.write("line1 content\nline2 content\n")
        start=False
    if start == False:
        f.write(line)
f.close()