Created
November 19, 2024 13:35
-
-
Save Yggdrasill501/a761e28278eb96b984d4aa999eaf805f to your computer and use it in GitHub Desktop.
Fast search and replace in dir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
def replace_word_in_file(file_path, word_to_search, replacement_word): | |
with open(file_path, 'r', encoding='utf-8') as file: | |
content = file.read() | |
# Regular expression to match words within string literals | |
# This handles both single and double quotes | |
pattern = re.compile(r'(["\'])(.*?)(\b' + re.escape(word_to_search) + r'\b)(.*?)\1') | |
# Replace the word within the matched strings | |
content = pattern.sub(lambda m: m.group(1) + m.group(2) + replacement_word + m.group(4) + m.group(1), content) | |
with open(file_path, 'w', encoding='utf-8') as file: | |
file.write(content) | |
def replace_word_in_repository(directory, word_to_search, replacement_word): | |
for root, dirs, files in os.walk(directory): | |
for file in files: | |
# Process only TypeScript files | |
if file.endswith(('.ts', '.tsx')): | |
file_path = os.path.join(root, file) | |
replace_word_in_file(file_path, word_to_search, replacement_word) | |
if __name__ == '__main__': | |
path_to_repo = input(" what is your path") | |
word_to_search = input("What are you searching for" ) | |
replacement_word = input("What are you replacing it with") | |
replace_word_in_repository(path_to_repo, word_to_search, replacement_word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment