Home > Software engineering >  Replace part of a Line in a File
Replace part of a Line in a File

Time:12-05

I would like to search for a line in the file using a pattern and partially replace it

the word "tribual" is unique in the file

the file looks like this:

userfile
indirect
/home/test
15238 8687 45688
stats 887 558 998
tribual 45688 786661 786661 -223811
home test
indirect test 1048576
indirect backup 45688

I would like to replace the line tribual, whereby the 2nd digit 1048576 must not be changed!

example:

old:
tribual 45688 786661 786661 -223811
new:
tribual 45688 1048576 1048576 1048576

the 2nd digit 45688 is always different.

I don't know how I can leave out the 2nd digit to replace it

import os

arr = os.listdir('/opt/files/')
for ufiles in arr:
    f = open(ufiles, 'r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace('tribual 45688 786661 786661 -223811', 'tribual 45688 1048576 1048576 1048576')

    f = open(ufiles, 'w')
    f.write(newdata)
    f.close()

many thanks for the help

CodePudding user response:

You could use a regular expression:

import re

newdata = re.sub(
    r'^(tribual \S ).*$',
    r'\1 1048576 1048576 1048576',
    filedata,
    flags=re.MULTILINE)

Breakdown:

  • ^ - Start of line (with re.MULTILINE)
  • (...) - Match group, which is then retrieved with \1 in the replacement pattern
  • \S - One or more non-whitespace characters, i.e. '45688' in this case
  • .* - Anything
  • $ - End of line (with re.MULTILINE)

Docs: re.sub()

Try it online: regex101

  • Related