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)