From a96e498f7c877b59ce63af89e842b48bc432c97f Mon Sep 17 00:00:00 2001 From: Stefano Serafin <serafin@jet01.img.univie.ac.at> Date: Fri, 7 Feb 2025 16:03:11 +0100 Subject: [PATCH] utility script for bulk replacement of text bits in several files --- replace_text.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 replace_text.py diff --git a/replace_text.py b/replace_text.py new file mode 100644 index 0000000..37504e7 --- /dev/null +++ b/replace_text.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Useful in order to edit +# a set of config files all at once + +# https://stackoverflow.com/questions/74191831/how-to-replace-a-text-with-another-text-in-several-txt-files-at-the-same-time + +import glob +import os + +# Input and output text files +pathSource = "./config_files/" +pathDest = "./config_files_new/" +textFiles_Source = glob.glob(pathSource+"*.json") +textFiles_Dest = [i.replace(pathSource,pathDest) for i in textFiles_Source] + +if not os.path.exists(pathDest): + os.makedirs(pathDest) + +# searched text and replacement text +search_text = '"nens": 20' +replace_text = '"nens": 200' + +# Loop over each text file in our list from above +for source,dest in zip(textFiles_Source,textFiles_Dest): + # Opening our text file in read only + # mode using the open() function + with open(source, 'r') as file: + + # Reading the content of the file + # using the read() function and storing + # them in a new variable + data = file.read() + + # Searching and replacing the text + # using the replace() function + data = data.replace(search_text, replace_text) + + # Opening our text file in write only + # mode to write the replaced content + with open(dest, 'w') as file: + + # Writing the replaced data in our + # text file + file.write(data) -- GitLab