Home > Enterprise >  Find IP address in multiple text files and replace it with another string in Python with regex
Find IP address in multiple text files and replace it with another string in Python with regex

Time:05-11

I have multiple text files as below:

I want to read all of the text files and find the IP value in each file and replace it with the noresult string which is available in the text and save per file in python.

Text1

     Id                = 0005      
     Cause          = ERROR      
     Code     = 307      
     Event Time              = 2020-11-09 10:16:48      
     Severity      = WARNING      
     Severity Code = 5     
     result = noresult
     Id                = 0006      
     Cause          = FAILURE      
     Code     = 517      
     Event Time              = 2020-11-09 10:19:47      
     Severity      = MINOR      
     Severity Code = 4 result = noresult 
     ip[10.1.1.1

Text2

 Id                = 0007      
 Cause          = ERROR      
 Code     = 307      
 Event Time              = 2020-11-09 10:16:48      
 Severity      = WARNING      
 Severity Code = 5      
 Id                = 0008      
 Cause          = FAILURE 
 result = noresult     
 Code     = 517      
 Event Time              = 2020-11-09 10:19:47      
 Severity      = MINOR      
 Severity Code = 4  
 result = noresult
 ip[10.1.1.3

Needful result:

Text1

 Id                = 0005      
 Cause          = ERROR      
 Code     = 307      
 Event Time              = 2020-11-09 10:16:48      
 Severity      = WARNING      
 Severity Code = 5     
 result = 10.1.1.1
 Id                = 0006      
 Cause          = FAILURE      
 Code     = 517      
 Event Time              = 2020-11-09 10:19:47      
 Severity      = MINOR      
 Severity Code = 4 result = 10.1.1.1
 ip[10.1.1.1

Text2

 Id                = 0007      
 Cause          = ERROR      
 Code     = 307      
 Event Time              = 2020-11-09 10:16:48      
 Severity      = WARNING      
 Severity Code = 5      
 Id                = 0008      
 Cause          = FAILURE 
 result = 10.1.1.3
 Code     = 517      
 Event Time              = 2020-11-09 10:19:47      
 Severity      = MINOR      
 Severity Code = 4  
 result = 10.1.1.3
 ip[10.1.1.3

CodePudding user response:

If the ip is always your last field you can simply do this:

txt = txt.replace("noresult", txt.split("ip[")[-1])

In details, if you want to read, modify and write:

txt = open("filename.txt", "r").read()
txt = txt.replace("noresult", txt.split("ip[")[-1])
open("filename.txt", "w").write(txt)

If you have more files, you can group their paths in a list file_list = ["file1.txt", "file2.txt", ... ] and then repeat the above procedures cycling on this list:

for filepath in file_list:
    txt = open(filepath, "r").read()
    txt = txt.replace("noresult", txt.split("ip[")[-1])
    open(filepath, "w").write(txt)
  • Related