The most simple usage is as follows:
$ replace.py 'foobarz' 'foo bar' myfile.txt
The tool searches for foobarz
on the contents of myfile.txt and replaces it with foo bar
.
The result is written on stdout. This is useful to check if the script is doing what you expect.
If you want the tool to change de file itself, use the -I
argument
(use backups or versioning to avoid losing data):
$ replace.py -I 'foobarz' 'foo bar' myfile.txt
To replace on multiple files recursively use find
together:
$ find . -name *.txt -exec replace.py -I 'foobarz' 'foo bar' {} \;
This tool was made specially to do replacements with regex.
The script actually uses Python's re.sub
to perform the replacements.
Refer to the official docs for details.
$ find . -name '*.py' -exec replace.py -I '(\W)(f|foo|foobar)\.tostr\(\)' '\1str(\2)' {} \;
The example above searches for all Python files recursively and replaces all calls to f.tostr()
, foo.tostr()
and foobar.tostr()
with str(f)
, str(foo)
or str(foobar)
.
Read the tool's help text for the available arguments to control the re.sub
behavior.