I have a text file like this:
line 1
line 2
line 3
CommandLine arguments "render -h 192.168.1.1 -u user -p pass"
line 5
I want to replace the IP address and write the file in-place. The tricky part is, the lines might be in a different order, and the command-line arguments might be written in a different order. So I need to find the line beginning with CommandLine and then replace the string between -h and the next -.
So far, I am able to get the old IP address with the following code, but I don't know how to replace it and write the file. I'm a Python beginner.
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)
Try this using 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='')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With