1

in a text file I want to search for a line containing specific text and at the next line I want to substitute beginning of a line with #(comment it out) inplace:

Example - before:

#test search 123
text to be commented out
#test 123

Example - wanted:

#test search 123
#text to be commented out
#test 123

I can do it via sed:

sed -i '/^#test search 123/!b; n; s/^/#/' test_file

but i was wondering if I'm able to do it natively in python.

2
  • possible duplicate of 'in-place' string modifications in Python Commented Jun 19, 2015 at 10:37
  • your sed is at least suspicious. correct will be sed -i '/pattern/ {N; s/\n/\n#/}' file. Any python solution will be longer. Commented Jun 19, 2015 at 11:21

2 Answers 2

1
import os

outfile = open('bla.txt.2', 'w')

search = "#test search 123"
flag = 0

with open('bla.txt', 'r') as f:

    for line in f:
        if flag == 1:
            mod_line = "#" + line
            outfile.write(mod_line)
            flag = 0
            continue

        outfile.write(line)
        if (search in line):
            flag = 1

outfile.close()

os.remove('bla.txt')
os.rename('bla.txt.2', 'bla.txt')
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answering. Works!!! So there is no chance to do the editing in-place without the second temp. file?
Not really, you could look into fileinput inplace but it still creates a temp backup file, so no dice.
0

Correct sed will be

sed -i '/pattern/ {N; s/\n/\n#/}' file  

This which follows maybe is not most pythonic way of same, specially if import re is needed for more complicated pattern then simple string

#! /usr/bin/env python3

pattern='some text'
f = open('input.txt', 'r')
g = open('output.txt', 'w')
l=f.readlines()
f.close()
for ind in range(len(l)):
    if pattern in l[ind]:
        l[ind+1]='#' + l[ind+1]
for field in l:
    g.write(field)
g.close()
print('Done')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.