Last active
August 27, 2021 21:48
-
-
Save ScriptAutomate/25d9aef4f093bfce515113472717867b to your computer and use it in GitHub Desktop.
Replace literal strings in files via Python
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
""" | |
Replace tool | |
Source: https://superuser.com/questions/422459/substitution-in-text-file-without-regular-expressions | |
""" | |
import re | |
import sys | |
search_term = sys.argv[1] | |
replace_term = sys.argv[2] | |
target_file = sys.argv[3] | |
insensitive = sys.argv[4] | |
with open(target_file, "r") as file: | |
content = file.read() | |
if insensitive == "True": | |
print(f"Ignore case: Replacing {search_term} with {replace_term} in {target_file}...") | |
insensitive_search = re.compile(re.escape(f"{search_term}"), re.IGNORECASE) | |
insensitive_search.sub(f"{replace_term}", content) | |
else: | |
print(f"Case sensitive: Replacing {search_term} with {replace_term} in {target_file}...") | |
content = content.replace(sys.argv[1], sys.argv[2]) | |
with open(target_file, "w") as file: | |
file.write(content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: