Linux uses the sed command to modify the kv style configuration file

  • 2020-12-13 19:15:54
  • OfStack

sed is a stream-oriented editor under unix, known as stream editor, which is line-oriented and works in action units, while sed is non-interactive and processes entire files once executed.

Daily background services configuration file exists in the form of key - value more, for example, toml ini file or 1 some custom configuration file, when we are in some cases, you need to write automation scripts to change the configuration files, we can through shell sed order regular matching rapid changes, simple and easy to 10 points, reduce a lot of "high-level language to write" trival, mainly listed below two kinds of common configuration changes and command reference example:

The configuration file test.conf for testing


$ cat test.conf 
max.connections = 100
test.log_path = "/tmp/test.log"
fsync=on

The way values are enclosed in quotes


#!/bin/bash
CONF=test.conf
set_key_value() {
  local key=${1}
  local value=${2}
  if [ -n $value ]; then
    #echo $value
    local current=$(sed -n -e "s/^\($key = '\)\([^ ']*\)\(.*\)$/\2/p" $CONF) # value With single quotes 
    if [ -n $current ];then
      echo "setting $CONF : $key = $value"
      value="$(echo "${value}" | sed 's|[&]|\\&|g')"
      sed -i "s|^[#]*[ ]*${key}\([ ]*\)=.*|${key} = '${value}'|" ${CONF}
    fi
  fi
}
set_key_value "max.connections" "1024"
set_key_value "test.log_path" "/data/logs/test.log"

The way values are not enclosed in quotes


CONF=test.conf
set_key_value() {
  local key=${1}
  local value=${2}
  if [ -n $value ]; then
    #echo $value
    local current=$(sed -n -e "s/^\($key = \)\([^ ']*\)\(.*\)$/\2/p" $CONF) # value No single quotes 
    if [ -n $current ];then
      echo "setting $CONF : $key = $value"
      value="$(echo "${value}" | sed 's|[&]|\\&|g')"
      sed -i "s|^[#]*[ ]*${key}\([ ]*\)=.*|${key} = ${value}|" ${CONF}
    fi
  fi
}
set_key_value "fsync" "off"

conclusion


Related articles: