From d4414c66f6c4d23b58e50c49d553bc695dbab608 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 16 Jan 2021 15:55:47 -0600 Subject: [PATCH] Add Extract Value From Command Output With Sed as a unix til --- README.md | 3 +- ...ract-value-from-command-output-with-sed.md | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 unix/extract-value-from-command-output-with-sed.md diff --git a/README.md b/README.md index 5b2c801..44a71cd 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). -_1011 TILs and counting..._ +_1012 TILs and counting..._ --- @@ -940,6 +940,7 @@ _1011 TILs and counting..._ - [Display The Contents Of A Directory As A Tree](unix/display-the-contents-of-a-directory-as-a-tree.md) - [Do Not Overwrite Existing Files](unix/do-not-overwrite-existing-files.md) - [Exclude A Directory With Find](unix/exclude-a-directory-with-find.md) +- [Extract Value From Command Output With Sed](unix/extract-value-from-command-output-with-sed.md) - [Figure Out The Week Of The Year From The Terminal](unix/figure-out-the-week-of-the-year-from-the-terminal.md) - [File Type Info With File](unix/file-type-info-with-file.md) - [Find Files With fd](unix/find-files-with-fd.md) diff --git a/unix/extract-value-from-command-output-with-sed.md b/unix/extract-value-from-command-output-with-sed.md new file mode 100644 index 0000000..10d7a59 --- /dev/null +++ b/unix/extract-value-from-command-output-with-sed.md @@ -0,0 +1,36 @@ +# Extract Value From Command Output With Sed + +As part of a shell script, you may need to extract a value from one command to +be used as part of a subsequent command. + +For instance, [I recently wrote a +script](https://gist.github.com/jbranchaud/3cda6be6e1dc69c6f55435a387018dac) +that needed to determine the version of the currently running Postges server. +The `postgres` command can tell me that. + +```bash +$ postgres -V +postgres (PostgreSQL) 12.3 +``` + +However, the output includes extra fluff that I don't need, namely the leading +`postgres (PostgreSQL) ` part. + +The output of `postgres` can be piped into a `sed` command that can extract +just what I need. + +```bash +$ postgres -V | sed -n 's/postgres (PostgreSQL) \(.*\)/\1/p' +12.3 +``` + +The `sed` command receives this single line of output and attempts a +substituation. It matches on `postgres (PostgresSQL) ` followed by a capture +group (`\(.*\)`) for the remaining characters. This capture group matches the +version part of the output. `sed` replaces everything in the first part of the +substitution with `\1`, which is `12.3`, and outputs that. + +The output of this could then be piped to another command or captured in a +variable to be used in the remainder of a script. + +[source](https://stackoverflow.com/a/24572880/535590)