Title: Extracting Config Values with grep Target Length: 90 seconds Word Count: 149 words
| Time | Visual / Screen Action | Audio (Narration) |
|---|---|---|
| 0:00 | Terminal window. Type: cat config.ini. The | Ever need to extract a specific value |
| screen shows a few lines, highlighting | from a config file? Let's say we need | |
| dbpassword = su-per-se-cret-%1 | to pull just the database password out | |
| of this file. | ||
| 0:30 | grep dbpassword config.ini \ | Typically, we'd grep for the key name, |
| awk -F' = ' '{print $2}' | in this case, "dbpassword," and then | |
| feed the output through awk to pull out | ||
| just the key value. | ||
| 0:60 | grep -o "dbpassword" config.ini | We could also try grepping for just the |
| key name, but all we'd get back is just | ||
| the key name, not the value we need. | ||
| 0:80 | ggrep -oP "dbpassword = \K.*" config.ini | To get just the value, we need the -P |
| flag for "Perl-compatible regex," and a | ||
| special regex sequence: backslash K. It | ||
| tells grep: "Match everything up to this | ||
| point, but then drop it from the final | ||
| output, and only keep what comes next." | ||
| 1:10 | sup-er-se-cret-%1 | The terminal outputs only the password, |
| which is perfectly isolated input for | ||
| your bash scripts. Note that we're using | ||
| ggrep here, because I'm running on BSD | ||
| Unix, which doesn't support grep -P. No | ||
| worries there. |