GAS85
GAS85

Reputation: 13

Update YAML parameter file from CLI

I have a question regarding mkdocs YAML file update from the CLI. YAML file has following string:

...
site_name: Material for MkDocs
...

What I need is to manipulate site_name parameter:

  1. add src/ before
  2. remove all spaces and special characters from parameter.

Output should be:

...
site_name: src/MaterialforMkDocs
#OR
site_name: src/Material_for_MkDocs
...

I did following and looks that it's working:

newSiteName=$(grep "site_name:" mkdocs.yml | sed 's/ //g' | sed 's/[^a-z  A-Z 0-9 _]//g' | sed 's/site_name/site_name: src\//')

sed -i "s|site_name:.*|$newSiteName|" mkdocs.yml

I strongly believe that this could be solved in much easy way.

Upvotes: 0

Views: 800

Answers (2)

Mike Farah
Mike Farah

Reputation: 2584

You can also use yq - a tool specifically for yaml docs, including editing front-matter:

yq e --front-matter=process '.site_name |= "src/" + sub("[^a-zA-Z]", "")' file.yaml

See https://mikefarah.gitbook.io/yq/usage/front-matter#process-front-matter

Disclosure: I wrote yq

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246807

One call to sed:

sed -E '
    /^[[:blank:]]*site_name:[[:blank:]]*/ {
        h                       ;# copy the line
        s///                    ;# remove the previous regex
        s/[[:blank:]]+/_/g      ;# convert whitespace to underscores
        s,^,src/,               ;# add the prefix
        x                       ;# swap hold and pattern spaces
        s/:.*/: /               ;# remove the value
        G                       ;# append the hold space
        s/\n//                  ;# remove the newline
    }
' mkdocs.yml

If it looks right; add the -i option.

Upvotes: 1

Related Questions