From a330281f2656079b4d78ec6965f88bc48c762b34 Mon Sep 17 00:00:00 2001 From: Gregory Date: Sun, 23 Dec 2018 22:57:36 -0500 Subject: [PATCH] Update README.md --- README.md | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/README.md b/README.md index 90ddd4a..f89ebed 100644 --- a/README.md +++ b/README.md @@ -32,3 +32,79 @@ Some cherry-picked examples, where `sd` shines: Note: although `sed` has a nicer regex syntax with `-r`, it is not portable and doesn't work on, say, MacOS or Solaris. +## Guide + +1. By default, expressions are treated as literals. + +```sh +> echo "lots((([]))) of special chars" | sd "((([])))" "" +lots of special chars +``` + +Use `-r` or `--regex` to enable regex. + +2. Basic regex use - let's trim some trailing whitespace + +```sh +> echo "lorem ipsum 23 " | sd -r '\s+$' '' +lorem ipsum 23 +``` + +3. Capturing useful information. + +Indexed capture groups: + +```sh +> echo "cargo +nightly watch" | sd -r '(\w+)\s+\+(\w+)\s+(\w+)' 'cmd: $1, channel: $2, subcmd: $3' +cmd: cargo, channel: nightly, subcmd: watch +``` + +Named capture groups: + +```sh +> echo "123.45" | sd -r '(?P\d+)\.(?P\d+)' '$dollars dollars and $cents cents' +123 dollars and 45 cents +``` + +If you stumble upon any ambiguities, just use `${1}` instead of `$1`: + +```sh +> echo "123.45" | sd -r '(?P\d+)\.(?P\d+)' '$dollars_dollars and $cents_cents' + and +> echo "123.45" | sd -r '(?P\d+)\.(?P\d+)' '${dollars}_dollars and ${cents}_cents' +123_dollars and 45_cents +``` + +You may choose to always use `${1}` or only add as necessary. + + +4. Find & replace in files + +```sh +> sd "window.fetch" "fetch" -i http.js +``` + +That's it. + +Do a dry run: + +```sh +> sd "window.fetch" "fetch" < http.js | less +``` + +5. Find & replace across your project + +Good ol' unix philosophy to the rescue. + +```sh +fd -t f --exec sd 'from "react"' 'from "preact"' -i {} +``` + +Same, but with backups (consider version control). + +```bash +for file in $(fd -t f); do + cp "$file" "$file.bk" + sd 'from "react"' 'from "preact"' -i "$file"; +done +```