File tree 2 files changed +38
-1
lines changed 2 files changed +38
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
10
10
11
11
For a steady stream of TILs, [ sign up for my newsletter] ( https://tinyletter.com/jbranchaud ) .
12
12
13
- _ 1011 TILs and counting..._
13
+ _ 1012 TILs and counting..._
14
14
15
15
---
16
16
@@ -940,6 +940,7 @@ _1011 TILs and counting..._
940
940
- [ Display The Contents Of A Directory As A Tree] ( unix/display-the-contents-of-a-directory-as-a-tree.md )
941
941
- [ Do Not Overwrite Existing Files] ( unix/do-not-overwrite-existing-files.md )
942
942
- [ 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 )
943
944
- [ Figure Out The Week Of The Year From The Terminal] ( unix/figure-out-the-week-of-the-year-from-the-terminal.md )
944
945
- [ File Type Info With File] ( unix/file-type-info-with-file.md )
945
946
- [ Find Files With fd] ( unix/find-files-with-fd.md )
Original file line number Diff line number Diff line change
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 )
You can’t perform that action at this time.
0 commit comments