How to insert a new string after a certain type of repeatable text in a .txt document

I want to insert a particular string after a text pattern but the problem here is the text pattern is repetitive and I don’t want my string to be pasted below every of those texts. For example, lets say the contents of text.txt are-

; include lig file "lig.itp"
#endif 

;include prot file "prot.itp"
#endif

I want to insert -

;include lig_restraint file "lig_res.itp"
#endif

after ; include lig file "lig.itp" #endif and NOT after ;include prot file "prot.itp" #endif.

Keep in mind the #endif is in a new line, so if i use the command-

sed 's/#endif/#endif\n;include lig_restraint file "lig_res.itp"\n#endif/' text.txt > text.temp.txt

mv text.temp.txt text.txt

I will be getting an output -

; include lig file "lig.itp"
#endif 
;include lig_restraint file "lig_res.itp"
#endif
;include prot file "prot.itp"
#endif
;include lig_restraint file "lig_res.itp"
#endif

which I don’t desire, is there anyway to solve this problem? Hopefully i comprehended my question in an understandable manner.

Thank you

awk '/^#endif/ && !ins {print ("#endif\n;include lig_restraint file \"lig_res.itp\"");ins=1};{print}' text.txt
links

https://www.linuxquestions.org/questions/linux-newbie-8/sed-stop-insert-the-line-after-the-first-occurrence-of-the-pattern-4175683364/

bash - how to add new line at the end with awk - Stack Overflow

1 Like