Skip to content

Instantly share code, notes, and snippets.

@ScriptAutomate
Last active August 27, 2021 21:48
Show Gist options
  • Save ScriptAutomate/25d9aef4f093bfce515113472717867b to your computer and use it in GitHub Desktop.
Save ScriptAutomate/25d9aef4f093bfce515113472717867b to your computer and use it in GitHub Desktop.
Replace literal strings in files via Python
"""
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)
@ScriptAutomate
Copy link
Author

ScriptAutomate commented Apr 7, 2021

Example usage:

for PAGE in $($EDIT_PAGES)
do
    python replace.py 'original_string' 'new_string' $PAGE True
done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment