File backed, key value store implemented with posix utilities

I imagine this is a pretty common thing to do.

Which posix utility for reads, which for writes? What are the most common file formats to do this with?

Is inplace modification possible?

My first thought was to use json and jq, but I’m interested in embracing the unix philosophy

Edit:

I don’t think there is a standard tool for that. Except for grep/awk/sed etc. But using this you will need to care about lot of other issues like locking, format, special characters, etc. https://unix.stackexchange.com/a/21950/551103

What if didn’t care about "locking, format, special characters" at all? Can someone give a minimalist implementation with grep/awk/sed

Asked By: Tom Huntington

||

For alphanumeric key-values:

kvfile="kvfile"

put() {
    if grep -q "^${1}=" "$kvfile"; then
        sed -i "s/^${1}=.*$/${1}=${2}/" "$kvfile"
    else
        echo "${1}=${2}" >> "$kvfile"
    fi
}

get() {
    grep "^${1}=" "$kvfile" | awk -F= '{printf "%s", $2}'
}

Martin Kealey actually knows how to script sed and awk and suggests:

put() {
    sed -i "/^$1=/{ h ; s/=.*/=$2/ ; } ; $ { p; g; /./d; s/^$/$1=$2/ ; }" "$kvfile";
}

get() { 
    awk -F= -vk="$1" '$1 == k{ print $2 }' "$kvfile";
}
Answered By: Tom Huntington
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.