How can I insert lines before a specific line?

Question:

Suppose the following file:

...

OW             8  16.000000  0.00000000  A     0.31507524       0.635968
HW             1   1.008000  0.00000000  A              0              0


[ moleculetype ]
; Name            nrexcl
system1          3

[ atoms ]
;   nr       type  resnr residue  atom   cgnr    charge       mass  typeB    chargeB      massB

...

I want to insert the lines

#ifdef POSRES
#include "posres.itp"
#endif

to the file like:

...

OW             8  16.000000  0.00000000  A     0.31507524       0.635968
HW             1   1.008000  0.00000000  A              0              0

#ifdef POSRES
#include "posres.itp"
#endif

[ moleculetype ]
; Name            nrexcl
system1          3

[ atoms ]
;   nr       type  resnr residue  atom   cgnr    charge       mass  typeB    chargeB      massB

...

I always want to insert the lines before [ moleculetype ].

Could you tell me how to realise it by python or bash?

Thanks,

Asked By: Natu

||

Answers:

The way I do this is that I make my own print function that will print it and add it to a list, as such:

sent = []
def log(message):
    sent.append(message)
    print(message)

Next, add a function to insert a message:

def add_message(index, message):
    sent.insert(index, message)
    clear_screen()
    resend()

Also add functions to clear the screen and resend all the messages. 50 lines or more in the shell will be squeezed, meaning 49 lines will be used.

def clear_screen():
    print("n"*49)

def resend():
    for message in sent:
        print(message)

For an example of it working, add the following code to the bottom of the file.

import time
clear_screen()
log("A")
time.sleep(1)
log("B")
time.sleep(1)
add_message(1, "C")
Answered By: KingsMMA
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.