Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find/replace string between two words in text file

Tags:

python

string

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)
like image 481
Elliott B Avatar asked Apr 03 '18 07:04

Elliott B


1 Answers

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='')
like image 150
bhansa Avatar answered Oct 05 '22 23:10

bhansa