From 7b512d0c4321b4899adb8e368b8f70ab09b603ee Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 8 Mar 2021 09:01:47 -0600 Subject: [PATCH] Add Output Only Lines Involved In A Substitution as a sed til --- README.md | 3 +- ...t-only-lines-involved-in-a-substitution.md | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 sed/output-only-lines-involved-in-a-substitution.md diff --git a/README.md b/README.md index 82079b9..5d59cb5 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). -_1076 TILs and counting..._ +_1077 TILs and counting..._ --- @@ -933,6 +933,7 @@ _1076 TILs and counting..._ - [Apply Multiple Substitutions To The Input](sed/apply-multiple-substitutions-to-the-input.md) - [Extract Value From Command Output With Sed](sed/extract-value-from-command-output-with-sed.md) +- [Output Only Lines Involved In A Substitution](sed/output-only-lines-involved-in-a-substitution.md) - [Use An Alternative Delimiter In A Substitution](sed/use-an-alternative-delimiter-in-a-substitution.md) ### Shell diff --git a/sed/output-only-lines-involved-in-a-substitution.md b/sed/output-only-lines-involved-in-a-substitution.md new file mode 100644 index 0000000..904f321 --- /dev/null +++ b/sed/output-only-lines-involved-in-a-substitution.md @@ -0,0 +1,38 @@ +# Output Only Lines Involved In A Substitution + +When you run a basic `sed` command, it will _autoprint_ the pattern space (a +line of input) once it is done running the script against it. That means every +line will get sent to stdout. + +You can supress the autoprint functionality with the `-n` flag like so: + +```bash +$ seq 100 | sed -n 's/1$/one/' +``` + +You can then add the `p` flag to the end of the substitute command to tell it +to _print_ any line that was affected by that substitution after the +substitution has been applied. + +```bash +$ seq 100 | sed -n 's/1$/one/p' +one +1one +2one +3one +4one +5one +6one +7one +8one +9one +``` + +For all numbers between 1 and 100, this matches those that end in `1` and +substitutes that `1` for `one`. And then it is only those lines that go to +stdout. + +If you used the `p` flag without `-n`, every line would autoprint and then +you'd get duplicate output for each line that had a substitution. + +See `man sed` for more details.