Skip to content

Commit 419f38b

Browse files
committed
add yaml editor function
1 parent 66b5bad commit 419f38b

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

misc/tools.func

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9724,3 +9724,44 @@ setup_nltk() {
97249724
97259725
return $rc
97269726
}
9727+
9728+
# ------------------------------------------------------------------------------
9729+
# Edit a key-value pair in a YAML configuration file.
9730+
#
9731+
# Description:
9732+
# - Finds the first occurrence of the given key in the YAML file and replaces
9733+
# its value in-place using sed.
9734+
# - Handles both quoted and unquoted values on the same line.
9735+
# - The key is matched at the start of a line (optionally preceded by spaces),
9736+
# followed by a colon and optional whitespace.
9737+
# - If the key is not found, the function exits with a non-zero status and
9738+
# prints an error message.
9739+
#
9740+
# Usage:
9741+
# edit_yaml_config "/opt/myapp/config.yml" "database_host" "localhost"
9742+
# edit_yaml_config "/opt/myapp/config.yml" "port" "5432"
9743+
#
9744+
# Parameters:
9745+
# $1 - Path to the YAML file
9746+
# $2 - Key to find (e.g. "database_host")
9747+
# $3 - New value to set (e.g. "localhost")
9748+
#
9749+
# Returns: 0 on success, 1 if the file does not exist or the key is not found
9750+
# ------------------------------------------------------------------------------
9751+
edit_yaml_config() {
9752+
local file="$1"
9753+
local key="$2"
9754+
local value="$3"
9755+
9756+
if [[ ! -f "$file" ]]; then
9757+
msg_error "edit_yaml_config: file not found: $file"
9758+
return 1
9759+
fi
9760+
9761+
if ! grep -qE "^[[:space:]]*${key}[[:space:]]*:" "$file"; then
9762+
msg_error "edit_yaml_config: key '${key}' not found in $file"
9763+
return 1
9764+
fi
9765+
9766+
sed -i "s|^\([[:space:]]*${key}[[:space:]]*:\).*|\1 ${value}|" "$file"
9767+
}

0 commit comments

Comments
 (0)