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
.