Here's a Python script that meets your requirements:
import os
import shutil
from pathlib import Path
def load_needles(filename):
"""Load strings to be replaced from a file."""
try:
with open(filename, 'r') as f:
# Read lines, strip whitespace, and filter out empty lines
needles = [line.strip() for line in f if line.strip()]
return needles
except FileNotFoundError:
print(f"Error: {filename} not found")
return []
except Exception as e:
print(f"Error reading {filename}: {str(e)}")
return []
def replace_with_x(content, needles):
"""Replace all occurrences of needles with X's of the same length."""
modified_content = content
for needle in needles:
if needle: # Skip empty strings
replacement = 'X' * len(needle)
modified_content = modified_content.replace(needle, replacement)
return modified_content
def process_file(filepath, needles):
"""Process a single file, replacing needles with X's."""
try:
# Read original content
with open(filepath, 'r', encoding='utf-8') as f:
original_content = f.read()
# Create modified content
modified_content = replace_with_x(original_content, needles)
# If no changes were made, skip writing
if modified_content == original_content:
return True
# Create temporary file in the same directory
temp_file = filepath + '.tmp'
# Write to temporary file
with open(temp_file, 'w', encoding='utf-8') as f:
f.write(modified_content)
# If we got here, writing was successful, so replace original file
shutil.move(temp_file, filepath)
print(f"Successfully processed: {filepath}")
return True
except Exception as e:
print(f"Error processing {filepath}: {str(e)}")
# Clean up temporary file if it exists
if os.path.exists(temp_file):
try:
os.remove(temp_file)
except:
pass
return False
def process_directory(directory, needles):
"""Recursively process all files in a directory."""
if not os.path.exists(directory):
print(f"Error: Directory '{directory}' does not exist")
return
# Convert to Path object for easier handling
dir_path = Path(directory)
# Counter for processed files
processed_count = 0
error_count = 0
# Recursively iterate through all files
for filepath in dir_path.rglob('*'):
if filepath.is_file():
if process_file(filepath, needles):
processed_count += 1
else:
error_count += 1
print(f"\nProcessing complete:")
print(f"Files successfully processed: {processed_count}")
print(f"Files with errors: {error_count}")
def main():
# Configuration
needles_file = 'ids.txt'
logs_directory = 'logs'
# Load needles
needles = load_needles(needles_file)
if not needles:
print("No strings to replace. Exiting.")
return
print(f"Loaded {len(needles)} strings to replace")
# Process the directory
process_directory(logs_directory, needles)
if __name__ == '__main__':
main()
This script:
-
Defines several functions:
load_needles: Loads the strings to replace from 'ids.txt'
replace_with_x: Replaces matched strings with X's
process_file: Processes a single file using a temporary file
process_directory: Recursively processes all files in a directory
main: Orchestrates the overall execution
-
Features:
- Error handling for file operations
- Uses temporary files to ensure safe file replacement
- Recursively processes all files in the 'logs' directory
- Provides progress feedback and summary statistics
- Uses UTF-8 encoding for file operations
- Cleans up temporary files in case of errors
-
Usage:
- Create a file named 'ids.txt' with one string per line that you want to replace
- Create a directory named 'logs' containing the files you want to process
- Run the script
Example 'ids.txt':
ABC123
XYZ789
SECRET_TOKEN
Example usage:
- If a file in 'logs' contains "My secret is ABC123 and XYZ789",
- After running the script, it will contain "My secret is XXXXXX and XXXXXX"
The script will:
- Create a temporary file for each modified file
- Only replace the original if the temporary file was successfully written
- Print progress information
- Show a summary of how many files were processed and if there were any errors
Error handling includes:
- Missing input files
- File read/write errors
- Directory not found
- Cleanup of temporary files on error
To use the script, simply save it, create your 'ids.txt' file, put your files in the 'logs' directory, and run the script.