Rename or reshape matches
Rename or reshape matches
Replace each match with a template: ${name} renders a register, ${0} the whole match, and
${name:acc} a transform or a typed slice of one, chained with |. The
rewrite accessors lists them.
Keep part of each match
Bind the part to keep and render it alone. The closing tag must equal the opening one, =t,
so only well-formed pairs are touched:
$ trex rewrite '<\W:t>.*</=t>' '[${t}]' --text '<b>hi</b> <i>yo</i>'
[b] [i]
Reshape a typed value
A typed register slices by its structure: an IPv4 address by octetN-M, a URL by host, an
email by domain, a version by major, a timestamp by year.
$ trex rewrite '\I:ip' '${ip:octet1-2}.0.0/16' --text 'conn from 192.168.5.9'
conn from 192.168.0.0/16
Compute the replacement
Where a template cannot say it, hand each match to a function. Here durations are written in milliseconds whatever unit they were written in:
let pat = trex::parse(r"\R:t").expect("valid pattern");
let out = trex::rewrite_with(&pat, b"took 1500ms, then 2s", |m| match m.value("t") {
Some(trex::typed::TypedValue::Num(ns)) => format!("{}ms", ns.as_f64().expect("a number") / 1e6),
_ => m.text().to_string(),
});
assert_eq!(out, b"took 1500ms, then 2000ms");Rename across files
Look at the diff first, then write it:
$ cat src/notes.md
The answer is 42, and legacy_call() is the old name.
See legacy_call in the guide.
$ cat src/main.rs
fn main() {
legacy_call(42);
}
$ trex rewrite '"legacy_call"' 'current_call' src/ --dry-run
--- src/main.rs
+++ src/main.rs
@@ -1,3 +1,3 @@
fn main() {
- legacy_call(42);
+ current_call(42);
}
--- src/notes.md
+++ src/notes.md
@@ -1,2 +1,2 @@
-The answer is 42, and legacy_call() is the old name.
-See legacy_call in the guide.
+The answer is 42, and current_call() is the old name.
+See current_call in the guide.
$ trex rewrite '"legacy_call"' 'current_call' src/ --in-place
src/main.rs: 1 replacement
src/notes.md: 2 replacements
--interactive, and -Interactive in PowerShell, put each change to you instead, with one
answer covering every change of the same template.