Skip to content

Commit

Permalink
feat(#2947): add function to replace regex in file
Browse files Browse the repository at this point in the history
  • Loading branch information
jmv74211 committed Sep 21, 2022
1 parent a010b78 commit 04d7382
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions deps/wazuh_testing/wazuh_testing/tools/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import string
import xml.etree.ElementTree as ET
import zipfile
import re

import filetype
import requests
Expand Down Expand Up @@ -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)

0 comments on commit 04d7382

Please sign in to comment.