0

If I knew the first thing about Python, I'd have figured this out myself just by referring to other similar questions that were already answered.

With that out of the way, I'm hoping you can help me achieve the following:

I'm looking to replace all occurrences of IP addresses with the file name itself, in a directory, inline.

Let's say all my files are in D:\super\duper\directory\

Files don't have any extension, i.e., a sample file name will be "jb-nnnn-xy". Even if there are multiple mentions of IP address in the file, I'm interested in replacing only the line that looks like this (without quotes):

" TCPHOST = 72.163.363.25"

So overall, there are thousands of files in the directory, of which only few have hard-coded IP addresses.

And the line of interest should finally look like this:

" TCPHOST = jb-yyyy-nz"

where "jb-yyyy-nz" is the name of the file itself

Thank you very much for your time and help!

EDIT: Just a mish mash of code from other posts that I'm trying out..

from __future__ import print_function
import fnmatch
import os 
from fileinput import FileInput
import re

ip_addr_regex = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
def find_replace(topdir, text):
    for dirpath, dirs, files in os.walk(topdir, topdown=True):
        files = [os.path.join(dirpath, filename) for filename in files]
        for line in FileInput(files, inplace=True):
                print(line.replace(text, str(filename)))

find_replace(r"D:\testmulefew",ip_addr_regex)
oompaloompa
  • 3
  • 1
  • 5
  • Have you tried writing the code yourself? If yes, can you please show it? – Anmol Singh Jaggi Oct 13 '16 at 12:20
  • Updated the main post with the code I'm trying... I got "expected character buffer object" error with the function. When I ran it repeatedly, it also blanked out one file after another for each attempt. – oompaloompa Oct 13 '16 at 12:33

1 Answers1

0

Please check the below code with comments inline:

import os
import re
import fileinput
#Get the file list from the directory
file_list = [f for f in os.listdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")]

#Change the directory where file to checked and modify
os.chdir("C:\\Users\\dinesh_pundkar\\Desktop\\demo")

#FileInput takes file_list as input 
with fileinput.input(files=file_list,inplace=True) as f:
    #Read file line by line
    for line in f:
        d=''
        #Find the line with TCPHOST
        a = re.findall(r'TCPHOST\s*=\s*\d+\.',line.strip())
        if len(a) > 0:
           #If found update the line
            d = 'TCPHOST = '+str(fileinput.filename())
            print (d)
        else:
            #Otherwise keep as it is
            print (line.strip())

P.S: Assumed the directory contains file and it does not have other directory inside it. Otherwise, file listing need to do recursively.

Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37
  • I pressed enter before I could go onto the next line. – oompaloompa Oct 17 '16 at 06:14
  • Yet again... Anyway, I'm getting this error: Traceback (most recent call last): File "resolver.py", line 12, in with fileinput.input(files=file_list,inplace=True) as f: AttributeError: FileInput instance has no attribute '__exit__' – oompaloompa Oct 17 '16 at 06:14
  • Um... Seems Python 2.7.10 doesn't allow a context manager for fileinput. Got around it by following [this](https://stackoverflow.com/questions/30835090/attributeerror-fileinput-instance-has-no-attribute-exit/30835248#30835248). I'm able to run it now but it rewrites the whole file instead of just replacing the line...... – oompaloompa Oct 17 '16 at 06:27
  • 1
    Tweaked around a bit and now it works as required. Thank you! – oompaloompa Oct 17 '16 at 09:15