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)
Elliott B
  • 980
  • 9
  • 32
  • For changing a file in-place that you are also reading, look at ["Is it possible to modify lines in a file in-place?"](https://stackoverflow.com/a/5463419/7315159). – Niayesh Isky Apr 03 '18 at 07:23

2 Answers2

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='')
bhansa
  • 7,282
  • 3
  • 30
  • 55
  • Thank you, that works! Is there a reason you prefer FileInput() instead of input() ? – Elliott B Apr 03 '18 at 08:19
  • `input()` will also work the same, for more details check the docs. – bhansa Apr 03 '18 at 08:59
  • 1
    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='')` – Elliott B Apr 03 '18 at 09:31
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

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
  • 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. – Elliott B Apr 03 '18 at 07:44
  • Also — using the second method as you wrote removes all the other lines from the text file. – Elliott B Apr 03 '18 at 07:52
  • @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. – Vikas Periyadath Apr 03 '18 at 09:16