开发者

How to modify INI files from shell script?

I'm building a custom package of vnc and would like to ensure the xdcmp settings of GDM are enabled in the package post install script. The gdm.conf file is an ini style one, i.e开发者_StackOverflow社区.:

[section]
var=name

And the value I want to set has name clashes in different sections throughout the config file.

Are there any methods or tools that allow for easy manipulation of ini style config files from shell scripts?

I'd like to sort this out in the .deb postinst script.


Have a look at the crudini package. It's designed for manipulating ini files from shell


If you're willing to write some Perl, there's Config::IniFiles (package libconfig-inifiles-perl).


Shell command using Ex editor (to change the value of var key):

ex +"%s/^var=\zs.*/new_name/" -scwq config.ini

To support INI sections, use the following syntax:

ex +':/\[section\]/,$s/var=\zs.*/new_name/' -scwq config.ini

For reading values from INI files, see: How do I grab an INI value within a shell script?


Here is the shell function which can be helpful for editing INI values (not supporting sections):

# Set value in the INI file.
# Usage: ini_set [key] [value] [file]
ini_set()
{
  local key="$1"
  local value="$2"
  local file="$3"
  [ -f "$file" ]
  if [ -n "$value" ]; then
    if grep -q "$key" "$file"; then
      echo "INFO: Setting '$key' to '$value' in $(basename "$file")"
      ex +'%s#'"$key"'=\zs.*$#'"$value"'#' -scwq! "$file"
    else
      echo "$key=$value" >> "$file"
    fi
  else
    echo "WARN: Value for '$key' is empty, ignoring."
  fi
}

Here is shell function to read INI values (not supporting sections):

# Get value from the INI file.
# Usage: ini_get [key] (file)
ini_get()
{
  local key="$1"
  local file="$2"
  [ ! -s "$file" ] && return
  local value="$(grep -om1 "^$key=\S\+" "$file" | head -1 | cut -d= -f2-)"
  echo "Getting '$key' from $(basename "$file"): $value" >&2
  echo $value
}

E.g. ini_get var.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜