Parse out key=value pairs into variables

后端 未结 5 1383
遇见更好的自我
遇见更好的自我 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:30

    Since discussion in commentary has made it clear that a pure-bash solution would also be acceptable:

    #!/bin/bash
    #      ^-- must be /bin/bash, not /bin/sh
    #
    # ...must also be bash 4.0 or newer.
    
    while read -r -a words; do                # iterate over lines of input
      declare -A vars=( )                  # refresh variables for each line
      set -- "${words[@]}"                 # update positional parameters
      for word; do
        if [[ $word = *"="* ]]; then       # if a word contains an "="...
           vars[${word%%=*}]=${word#*=}    # ...then set it as an associative-array key
        fi
      done
      echo "${vars[Var]} $5"              # Here, we use content read from that line.
    done <<<"Version=2 Len=17 Hello Var=Howdy Other"
    

    The <<<"Input Here" could also be , in which case lines in the file would be iterated over.

    If you wanted to use $Var instead of ${vars[Var]}, then substitute printf -v "${word%%=*}" %s "${word*=}" in place of vars[${word%%=*}]=${word#*=}, and remove references to vars elsewhere. Note that this doesn't allow for a good way to clean up variables between lines of input, as the associative-array approach does.

提交回复
热议问题