import re
import sys
def replace_log_values(log_file_path, replacements):
"""
Replaces values in a log file with specified replacements.
Performs synchronous execution.
Args:
log_file_path (str): The path to the log file.
replacements (dict): A dictionary where keys are the values to find
and values are the replacements.
"""
try:
with open(log_file_path, 'r') as f:
log_content = f.read()
for find_str, replace_str in replacements.items():
# Use re.escape to handle special characters in the find string
pattern = re.escape(find_str)
log_content = re.sub(pattern, replace_str, log_content)
with open(log_file_path, 'w') as f:
f.write(log_content)
except FileNotFoundError:
print(f"Error: File not found at {log_file_path}")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {e}")
sys.exit(1)
if __name__ == "__main__":
# Example Usage:
if len(sys.argv) != 3:
print("Usage: python replace_values.py <log_file_path> <replacements_dict>")
sys.exit(1)
log_file_path = sys.argv[1]
replacements_str = sys.argv[2]
try:
replacements = eval(replacements_str) # Evaluate the string as a dictionary
except Exception as e:
print(f"Error parsing replacements: {e}")
sys.exit(1)
replace_log_values(log_file_path, replacements)
Add your comment