From 88f49de7f3c2a53163bb4bcec7358d0661bbd83e Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 1 Dec 2025 14:07:25 -0600 Subject: [PATCH] Add Reference The Full Match In The Replacement as a Sed TIL --- README.md | 3 ++- ...rence-the-full-match-in-the-replacement.md | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 sed/reference-the-full-match-in-the-replacement.md diff --git a/README.md b/README.md index 5fcbd6e..e1c59dc 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://visualmode.kit.com/newsletter). -_1705 TILs and counting..._ +_1706 TILs and counting..._ See some of the other learning resources I work on: @@ -1500,6 +1500,7 @@ If you've learned something here, support my efforts writing daily TILs by - [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) +- [Reference The Full Match In The Replacement](sed/reference-the-full-match-in-the-replacement.md) - [Use An Alternative Delimiter In A Substitution](sed/use-an-alternative-delimiter-in-a-substitution.md) ### Shell diff --git a/sed/reference-the-full-match-in-the-replacement.md b/sed/reference-the-full-match-in-the-replacement.md new file mode 100644 index 0000000..6528f90 --- /dev/null +++ b/sed/reference-the-full-match-in-the-replacement.md @@ -0,0 +1,27 @@ +# Reference The Full Match In The Replacement + +The `&` can be used in the replacement part of a `sed` expression as reference +to the string match for this iteration of the expression. The occurrence of `&` +will be replaced with that entire match. + +As the `sed` man page puts it: + +> An ampersand (“&”) appearing in the replacement is replaced by the string +> matching the RE. + +I made use of this recently with [a `sed` expression that was evaluating a list +of filenames that I wanted to construct into a sequence of `mv` +commands](unix/rename-a-bunch-of-files-by-constructing-mv-commands.md). I needed +the filename that I was matching on to appear as the first argument of the `mv` +command I was constructing. + +Here is what that looks like: + +```bash +$ ls *.pdf | + sed 's/\(..\)\(..\)\(..\) Statement\.pdf/mv "&" "20\3-\1-\2-statement.pdf"/' +``` + +Notice right after `mv` in literal quotes is the `&`. That will be replaced in +the resulting replacement with the full matching string of the regular +expression in the first part of the sed statement (`s//`).