How to modify INI files from shell script?

帅比萌擦擦* 提交于 2020-07-21 07:42:33

问题


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.:

[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.


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/3466318/how-to-modify-ini-files-from-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!