TIL - Parse command output from shell
TIL, Today I Learned, is more of a "I just figured this out: here are my notes, you may find them useful too" rather than a full blog post
Parse text output in shell scripts is something that is needed every now and then. It used to be some clever pipeline with regular expressions, grep, cut or even awk.
But now I've started to use read for such things, and it has helped me a lot.
Consider the following example:
1mmcli -L
2 /org/freedesktop/ModemManager1/Modem/0 [Sierra Wireless] HL7812
Some parts of this string are dynamic, namely ModemManager1, 0 and [Sierra Wireless] HL7812.
So, If I want to parse and store these strings into variables, I could simple do:
1IFS='/ ' read -r _ _ _ mm _ mn mt < <(mmcli -L)
- IFS='/ ' Sets / or space as input field separators
- read -r _ _ _ mm _ mn mt: Read 4th, 6th and 7th onwards test in variable mm, mn and mt while ignoring rest
- < <(mmcli -L): Command substitution to invoke mmcli -L and feed it's output to read
This result is stored in mm, mn and mt:
1declare -p mm mn mt
2declare -- mm="ModemManager1"
3declare -- mn="0"
4declare -- mt="[Sierra Wireless] HL7812"
Pretty neat.