Parse out key=value pairs into variables

后端 未结 5 1382
遇见更好的自我
遇见更好的自我 2020-11-27 21:37

I have a bunch of different kinds of files I need to look at periodically, and what they have in common is that the lines have a bunch of key=value type strings

5条回答
  •  离开以前
    2020-11-27 22:11

    $ cat file | sed -r 's/[[:alnum:]]+=/\n&/g' | awk -F= '$1=="Var"{print $2}'
    Howdy Other
    

    Or, avoiding the useless use of cat:

    $ sed -r 's/[[:alnum:]]+=/\n&/g' file | awk -F= '$1=="Var"{print $2}'
    Howdy Other
    

    How it works

    • sed -r 's/[[:alnum:]]+=/\n&/g'

      This places each key,value pair on its own line.

    • awk -F= '$1=="Var"{print $2}'

      This reads the key-value pairs. Since the field separator is chosen to be =, the key ends up as field 1 and the value as field 2. Thus, we just look for lines whose first field is Var and print the corresponding value.

提交回复
热议问题