Code for parsing a key/value in in file from shell script

前端 未结 6 1874
心在旅途
心在旅途 2020-11-30 06:44

I have a file that I need to look up a value by key using a shell script. The file looks like:

HereIsAKey This is the value

How can I do so

6条回答
  •  一生所求
    2020-11-30 07:38

    I use a property file that is shared across multiple languages, I use a pair of functions:

    load_properties() {
        local aline= var= value=
        for file in config.properties; do
            [ -f $file ] || continue
            while read aline; do
                aline=${aline//\#*/}
                [[ -z $aline ]] && continue
                read var value <<<$aline
                [[ -z $var ]] && continue
                eval __property_$var=\"$value\"
                # You can remove the next line if you don't need them exported to subshells
                export __property_$var
            done <$file
        done
    }
    
    get_prop() {
        local var=$1 key=$2
        eval $var=\"\$__property_$key\"
    }
    

    load_properties reads from the config.properties file populating a set of variables __property_... for each line in the file, get_prop then allows the setting of a variable based on loaded properties. It works for most of the cases that are needed.

    Yes, I do realize there's an eval in there, which makes it unsafe for user input, but it works for what I needed it to do.

提交回复
热议问题