0

I have a YAML file that's about 25K lines and I have about 450 instances where I need to insert between two specific lines.

Here's an example of the file entries:

- changeSet:
    id: 1554756073258-367
    author: foo@bar.com
    changes:
    - createTable:
        columns:
        - column:
            constraints:
              nullable: false
            name: name
            type: VARCHAR(50)
        tableName: bazTable
- changeSet:
    id: 1554756073258-812
    author: foo@bar.com
    changes:
    - createTable:
        columns:
        - column:
            constraints:
              nullable: false
            name: name
            type: VARCHAR(50)
        tableName: barTable
- changeSet:
    id: 1555517850-1
    author: foo@bar.com
    changes:
      - dropDefaultValue:
          tableName: fooTable
          columnName: variable_id
      - dropDefaultValue:
          tableName: fooTable
          columnName: name
      - dropDefaultValue:
          tableName: fooTable
          columnName: method
      - dropDefaultValue:
          tableName: fooTable
          columnName: instance
      - dropDefaultValue:
          tableName: fooTable
          columnName: machine
      - dropDefaultValue:
          tableName: fooTable
          columnName: message
      - dropDefaultValue:
          tableName: fooTable
          columnName: action
      - dropDefaultValue:
          tableName: fooTable
          columnName: condition
      - dropDefaultValue:
          tableName: fooTable
- changeSet:
    id: 1555509481-1
    author: foo@bar.com
    preConditions:
    - onFail: MARK_RAN
    - tableExists:
        tableName: randomTable

What I'm trying to do is insert these three lines between author: and changes:

  preConditions:
  - onFail: MARK_RAN
  - tableExists:
      tableName: 

The catch is that I only want to do this when the entry begins with - changeSet:, ends with tableName: and contains createTable: between those two strings.

Below is how I would like it to look.

- changeSet:
    id: 1554756073258-812
    author: foo@bar.com
    preConditions:
      - onFail: MARK_RAN
      - tableExists:
          tableName: bazTable
    changes:
    - createTable:
        columns:
        - column:
            constraints:
              nullable: false
            name: name
            type: VARCHAR(50)
        tableName: bazTable

I've gotten so far writing the following command which prints out all sections that begin, end, and contain my specified strings

sed -n '/changeSet/{:a;N; /tableName/!ba; /createTable/p};' File.yaml

I just can't figure out how to get it to edit the file and add the missing section.

  • 1
    I think it would be easier and safer to do that with a yaml parser, e.g. python yaml module. – pLumo Apr 18 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.