💻
CODE SNIPPET — Aug 15, 2026Bash: Parse Any Key-Value Output into Structured Data
A single, reusable function that extracts key-value pairs from messy text output —
systemctl status,
/proc/cpuinfo,
openssl x509,
git config,
.env files, and more. Handles inconsistent whitespace, embedded delimiters (colons in URLs), and multiple delimiter types.
kv_parse() {
local input="$1"
local mode="${2:-pairs}"
local target="${3:-}"
echo "$input" | while IFS= read -r line; do
# Match KEY: VALUE, KEY=VALUE, or KEY VALUE
if [[ "$line" =~ ^[[:space:]]*([^:=[:space:]]+)[[:space:]]*[:=][[:space:]]*(.+)$ ]]; then
local key="${BASH_REMATCH[1]}"
local value="${BASH_REMATCH[2]}"
value="${value%%[[:space:]]}" # trim trailing whitespace
if [[ "$mode" == "get" && "$key" == "$target" ]]; then
echo "$value"
return 0
elif [[ "$mode" == "pairs" ]]; then
echo "${key}=${value}"
fi
fi
done
}
Single value extraction:# Get just the model from /proc/cpuinfo
kv_parse "$(cat /proc/cpuinfo)" "get" "model name"
# → Intel(R) Core(TM) i7-10700K
# Extract a specific .env value
kv_parse "$(cat .env)" "get" "DATABASE_URL"
Batch mode — iterate all pairs:kv_parse "$(git config -l)" "pairs" | while IFS='=' read -r key value; do
echo "Config: [$key] → $value"
done
💡
Pro tip: Combine with
--get in scripts to extract specific values from any tool's output without brittle
grep | sed chains. Works with
: or
= delimiters automatically.