在文本文件中查找/替换两个单词之间的字符串

Ell*_*t B 8 python string

我有这样的文本文件:

line 1
line 2
line 3
CommandLine arguments "render -h 192.168.1.1 -u user -p pass"
line 5
Run Code Online (Sandbox Code Playgroud)

我想替换IP地址并就地编写文件.棘手的部分是,行可能的顺序不同,命令行参数可能以不同的顺序写入.所以我需要找到以CommandLine开头的行,然后替换-h和下一个之间的字符串-.

到目前为止,我能够使用以下代码获取旧IP地址,但我不知道如何替换它并编写文件.我是Python的初学者.

with open(the_file,'r') as f:
    for line in f:
        if(line.startswith('CommandLine')):
            old_ip = line.split('-h ')[1].split(' -')[0]
            print(old_ip)
Run Code Online (Sandbox Code Playgroud)

bha*_*nsa 2

尝试使用这个fileinput

import fileinput, re
filename = 'test_ip.txt'
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(re.sub("-h \S+ -u", "-h YOUR_NEW_IP_HERE -u", line), end='')
Run Code Online (Sandbox Code Playgroud)