• Re: YAML: How to add additional lines after a specific line?

    From Greg Wooledge@21:1/5 to Anastasios Lisgaras on Wed Nov 6 23:00:01 2024
    On Wed, Nov 06, 2024 at 22:24:42 +0100, Anastasios Lisgaras wrote:
    I have a YAML file for example `resource.yaml`.
    I want to find in this file all the lines ( actually it should be only one
    ), with the following string: "resource_type: apple" and immediately after that line add the following lines:

    ```
    color: red
    weight: '1 kg'
    origin: "Country x"
    ```

    The *best* answer would be to find some kind of tool that's dedicated to editing YAML streams. I don't know YAML or its tools, so I have no recommendations there.

    If you want a second-best answer, you can use sed:

    hobbit:~$ seq 3 | sed $'/2/a\\\n color: red\\\n weight: \'1 kg\'\\\n origin: "Country x"'
    1
    2
    color: red
    weight: '1 kg'
    origin: "Country x"
    3

    The $'...' quoting is bash-specific, so this is actually a bash+sed answer.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From debian-user@howorth.org.uk@21:1/5 to Anastasios Lisgaras on Wed Nov 6 23:20:01 2024
    Anastasios Lisgaras <tasosnumberten@yahoo.gr> wrote:
    Hello community,

    I have a YAML file for example `resource.yaml`.
    I want to find in this file all the lines ( actually it should be
    only one ), with the following string: "resource_type: apple" and
    immediately after that line add the following lines:

    ```
    color: red
    weight: '1 kg'
    origin: "Country x"
    ```

    The result should be:

    ```
    resource_type:
    color: red
    weight: '1 kg'
    origin: "Country x"
    ```

    Just to note that your stated result doesn't appear to match your
    stated problem. The word 'apple' is missing.

    Any advice using awk, sed or something else ?

    Greg's answer is probably as good as any (I haven't tested it myself)
    FWIW, the YAML spec seems to be at https://yaml.org/spec/1.2.2/ though
    it's not needed.

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)