A simple command-line tool to perform regex-based string replacements in text files.
I needed it for programming.
Mainly implemented by Claude Sonnet 4.6.
- Use Python regular expressions to search and replace text.
- Supports a test mode (
-tflag) to preview changes line-by-line without modifying the file. - Handles common file errors gracefully (file not found, permission denied).
python replace_strings.py [-t] "search pattern" "replacement string" textfile-t(optional): Preview changes without modifying the file."search pattern": A Python regex pattern to search for."replacement string": The string to replace matches with.textfile: Path to the text file to modify.
Many examples can be found in test_replace_strings.py.
replace_strings.py "Hello" "Hi" mytext.txtNote that "hello" would not be replaced. The script works case sensitive.
replace_strings.py -t "Hello" "Hi" mytext.txtreplace_strings.py "\d+" "#" mytext.txtreplace_strings.py "(?m)^\s+$" "" mytext.txte.g. "John Smith" → "Smith, John"
replace_strings.py "(\w+) (\w+)" "\2, \1" mytext.txte.g. "2026-03-06" → "06.03.2026".
replace_strings.py "(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})" "\g<d>.\g<m>.\g<y>" mytext.txtNo installation required. Requires Python 3.7+.
The project includes a helper function in test_replace_strings.py to mirror the core replacement logic for testing purposes.
- Invalid regex patterns will print an error and exit.
- File not found or permission errors will print an error and exit.