Skip to content

Commit d4414c6

Browse files
committed
Add Extract Value From Command Output With Sed as a unix til
1 parent 07046e1 commit d4414c6

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1011 TILs and counting..._
13+
_1012 TILs and counting..._
1414

1515
---
1616

@@ -940,6 +940,7 @@ _1011 TILs and counting..._
940940
- [Display The Contents Of A Directory As A Tree](unix/display-the-contents-of-a-directory-as-a-tree.md)
941941
- [Do Not Overwrite Existing Files](unix/do-not-overwrite-existing-files.md)
942942
- [Exclude A Directory With Find](unix/exclude-a-directory-with-find.md)
943+
- [Extract Value From Command Output With Sed](unix/extract-value-from-command-output-with-sed.md)
943944
- [Figure Out The Week Of The Year From The Terminal](unix/figure-out-the-week-of-the-year-from-the-terminal.md)
944945
- [File Type Info With File](unix/file-type-info-with-file.md)
945946
- [Find Files With fd](unix/find-files-with-fd.md)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# Extract Value From Command Output With Sed
2+
3+
As part of a shell script, you may need to extract a value from one command to
4+
be used as part of a subsequent command.
5+
6+
For instance, [I recently wrote a
7+
script](https://gist.github.com/jbranchaud/3cda6be6e1dc69c6f55435a387018dac)
8+
that needed to determine the version of the currently running Postges server.
9+
The `postgres` command can tell me that.
10+
11+
```bash
12+
$ postgres -V
13+
postgres (PostgreSQL) 12.3
14+
```
15+
16+
However, the output includes extra fluff that I don't need, namely the leading
17+
`postgres (PostgreSQL) ` part.
18+
19+
The output of `postgres` can be piped into a `sed` command that can extract
20+
just what I need.
21+
22+
```bash
23+
$ postgres -V | sed -n 's/postgres (PostgreSQL) \(.*\)/\1/p'
24+
12.3
25+
```
26+
27+
The `sed` command receives this single line of output and attempts a
28+
substituation. It matches on `postgres (PostgresSQL) ` followed by a capture
29+
group (`\(.*\)`) for the remaining characters. This capture group matches the
30+
version part of the output. `sed` replaces everything in the first part of the
31+
substitution with `\1`, which is `12.3`, and outputs that.
32+
33+
The output of this could then be piped to another command or captured in a
34+
variable to be used in the remainder of a script.
35+
36+
[source](https://stackoverflow.com/a/24572880/535590)

0 commit comments

Comments
 (0)