BASH

Extract Key-Value Pairs from Configuration Files

A powerful Bash snippet to parse and extract specific configuration values (e.g., database host, API keys) from text-based configuration files using grep and awk.

#!/bin/bash
# Script to extract a specific value from a configuration file

CONFIG_FILE="config.ini"
KEY_TO_EXTRACT="DATABASE_HOST" # Example key to find

if [ ! -f "$CONFIG_FILE" ]; then
    echo "Error: Configuration file '$CONFIG_FILE' not found."
    exit 1
fi

VALUE=$(grep "^${KEY_TO_EXTRACT}=" "$CONFIG_FILE" | head -n 1 | awk -F'=' '{print $2}' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')

if [ -n "$VALUE" ]; then
    echo "The value for $KEY_TO_EXTRACT is: '$VALUE'"
else
    echo "Key '$KEY_TO_EXTRACT' not found or has no value in '$CONFIG_FILE'."
fi

# Example config.ini content:
# # This is a comment
# DATABASE_HOST = localhost
# API_KEY=abc123xyz
# DEBUG_MODE=true
How it works: This script extracts a specific configuration value by its key from a given file. It first uses `grep` to find the line containing the key, then `head -n 1` ensures only the first match is processed. `awk -F'=' '{print $2}'` splits the line by `=` and prints the second field (the value). Finally, `sed` is used to trim any leading/trailing whitespace around the extracted value.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs