BASH

Update Configuration Value in File using sed

Learn how to use `sed` in Bash to programmatically update specific configuration values within text files, useful for automated server setups.

#!/bin/bash

CONFIG_FILE="app.conf"
KEY_TO_UPDATE="DEBUG_MODE"
NEW_VALUE="false"

# Create a dummy config file for demonstration if it doesn't exist
if [ ! -f "$CONFIG_FILE" ]; then
  echo "# Application Configuration
DEBUG_MODE=true
PORT=8080
DB_HOST=localhost" > "$CONFIG_FILE"
  echo "Created dummy config file: $CONFIG_FILE"
fi


if [ -f "$CONFIG_FILE" ]; then
  # Use sed to find the line starting with KEY_TO_UPDATE and replace its value
  # The 'i' flag makes sed edit the file in-place
  sed -i "s/^\($KEY_TO_UPDATE=\).*/\\1$NEW_VALUE/" "$CONFIG_FILE"
  echo "Updated $KEY_TO_UPDATE to $NEW_VALUE in $CONFIG_FILE"
  echo "--- New $CONFIG_FILE content ---"
  cat "$CONFIG_FILE"
else
  echo "Error: Configuration file '$CONFIG_FILE' not found."
fi
How it works: This script uses the `sed` command-line utility to update a specific key-value pair in a configuration file. It finds lines that start with the `KEY_TO_UPDATE` and replaces the entire line after the key and equals sign with the `NEW_VALUE`. The `-i` option modifies the file in place. This is invaluable for automating configuration changes during deployments or system setups.

Need help integrating this into your project?

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

Hire DigitalCodeLabs