From b1c022f28fc914eda308d943c4503e73dbb12298 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 1 Apr 2021 14:43:11 -0500 Subject: [PATCH] Add Reference A Capture In The Regex as a sed til --- README.md | 3 ++- sed/reference-a-capture-in-the-regex.md | 32 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 sed/reference-a-capture-in-the-regex.md diff --git a/README.md b/README.md index 047269d..1df6c1e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1105 TILs and counting..._ +_1106 TILs and counting..._ --- @@ -956,6 +956,7 @@ _1105 TILs and counting..._ - [Grab All The Method Names Defined In A Ruby File](sed/grab-all-the-method-names-defined-in-a-ruby-file.md) - [OSX sed Does Regex A Bit Different](sed/osx-sed-does-regex-a-bit-different.md) - [Output Only Lines Involved In A Substitution](sed/output-only-lines-involved-in-a-substitution.md) +- [Reference A Capture In The Regex](sed/reference-a-capture-in-the-regex.md) - [Use An Alternative Delimiter In A Substitution](sed/use-an-alternative-delimiter-in-a-substitution.md) ### Shell diff --git a/sed/reference-a-capture-in-the-regex.md b/sed/reference-a-capture-in-the-regex.md new file mode 100644 index 0000000..8f5d6e7 --- /dev/null +++ b/sed/reference-a-capture-in-the-regex.md @@ -0,0 +1,32 @@ +# Reference A Capture In The Regex + +You create a capture group in a `sed` regex by wrapping a pattern in `\(` and +`\)`. Generally, this capture group is referenced in the substitution +expression with `\1`. + +The capture references (e.g. `\1`) can also be used in the regex as part of +specifying the match. + +For instance, we can do a capture of a single digit followed by a reference to +that capture. That will match any line that has a pair of matching consecutive +digits. + +```bash +$ seq 111 | sed -n 's/\([[:digit:]]\)\1/&/p' +11 +22 +33 +44 +55 +66 +77 +88 +99 +100 +110 +111 +``` + +This also uses `&` in the subex which represents the entire match. The `-n` and +`/p` combination suppresses printing of lines to only those that have +substitutions.