From 04d73820435e1b1e5ee82b62b293cf708228f24e Mon Sep 17 00:00:00 2001 From: jmv74211 Date: Wed, 21 Sep 2022 18:20:59 +0200 Subject: [PATCH] feat(#2947): add function to replace regex in file --- .../wazuh_testing/wazuh_testing/tools/file.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/deps/wazuh_testing/wazuh_testing/tools/file.py b/deps/wazuh_testing/wazuh_testing/tools/file.py index db633cd232..a6b69e8477 100644 --- a/deps/wazuh_testing/wazuh_testing/tools/file.py +++ b/deps/wazuh_testing/wazuh_testing/tools/file.py @@ -14,6 +14,7 @@ import string import xml.etree.ElementTree as ET import zipfile +import re import filetype import requests @@ -516,3 +517,26 @@ def download_text_file(file_url, local_destination_path): def get_file_lines(path): with open(path, "r+") as file_to_read: return file_to_read.readlines() + + +def replace_regex_in_file(search_regex, replace_regex, file_path): + """Perform replacements in a file data according to the specified regex. + + Args: + search_regex (list(str)): Search regex list. + replace_regex (list(str)): Replacements regex list. + file_path (str): File path to read and update. + """ + if (len(search_regex) != len(replace_regex)): + raise ValueError('search_regex has to have the same number of items than replace_regex. ' + f"{len(search_regex)} != {len(replace_regex)}") + + # Read the file content + file_data = read_file(file_path) + + # Perform the replacements + for search, replace in zip(search_regex, replace_regex): + file_data = re.sub(search, replace, file_data) + + # Write the file data + write_file(file_path, file_data)