1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 15:18:01 +00:00

Add Extract Value From Command Output With Sed as a unix til

This commit is contained in:
jbranchaud
2021-01-16 15:55:47 -06:00
parent 07046e17ad
commit d4414c66f6
2 changed files with 38 additions and 1 deletions

View File

@@ -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)

View File

@@ -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)