8

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)
1

2 Answers 2

2

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='')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that works! Is there a reason you prefer FileInput() instead of input() ?
input() will also work the same, for more details check the docs.
This put me on the right track. To make it more robust, handling arguments in a different order, I changed the line to print(re.sub('-h [\w.]+', '-h ' + new_ip, line), end='')
0

You can try this for replacing characters :

with open(the_file,'r') as f:
   for line in f:
      if(line.startswith('CommandLine')):
           replaced_line = re.sub('(?<=-h).*?(?=-u)', 'NEW IP',line, 
                       flags=re.DOTALL)

It will make the line like :

CommandLine arguments "render -h NEW IP -u user -p pass"

Another way you can try with fileinput, it will replace the old ip with what you want to add and will write to your file.

UPDATE :

The problem was with the if condition now with my first regex you can manage that if :

for line in fileinput.input("file.txt", inplace=True):
    print(re.sub('(?<=-h).*?(?=-u)',' newIp ',line.strip()), end='\n')

Note : Add space in new ip

3 Comments

In your first method, how do I then overwrite the line with replaced_line in the original file? I can't use the second option in this case because the order of arguments in the text file could be different, and I need to replace only the IP.
Also — using the second method as you wrote removes all the other lines from the text file.
@ElliottB I understood the problem with my code, It was with the condition So with using regex I managed to fix the issue. Any way happy to hear you got correct one. I have updated my answer, you can just take a look.

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.