I want to load a YAML file, possibly edit the data, and then dump it again. How can I preserve formatting?

Preface: Throughout this answer, I mention some popular YAML implementations. Those mentions are never exhaustive since I do not know all YAML implementations out there. I will use YAML terms for data structures: Atomic text content (even numbers) is a scalar. Item sequences, known elsewhere as arrays or lists, are sequences. A collection of key-value … Read more

How can I parse a YAML file from a Linux shell script?

Here is a bash-only parser that leverages sed and awk to parse simple yaml files: function parse_yaml { local prefix=$2 local s=”[[:space:]]*” w='[a-zA-Z0-9_]*’ fs=$(echo @|tr @ ‘\034’) sed -ne “s|^\($s\):|\1|” \ -e “s|^\($s\)\($w\)$s:$s[\”‘]\(.*\)[\”‘]$s\$|\1$fs\2$fs\3|p” \ -e “s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p” $1 | awk -F$fs ‘{ indent = length($1)/2; vname[indent] = $2; for (i in vname) {if (i > indent) … Read more

Use placeholders in yaml

Context YAML version 1.2 user wishes to include variable placeholders in YAML have placeholders replaced with computed values, upon yaml.load be able to use placeholders for both YAML mapping keys and values Problem YAML does not natively support variable placeholders. Anchors and Aliases almost provide the desired functionality, but these do not work as variable … Read more

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml: #!/usr/bin/env python import yaml with open(“example.yaml”, “r”) as stream: try: print(yaml.safe_load(stream)) except yaml.YAMLError as exc: print(exc) And that’s it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly … Read more