I am not able to find a way to append a line in yaml file after exact match of string but ignoring similar string having other values in it in a line. There are some example but that is not my case. I have a yaml file and I am automating its configuration instead of adding values manually by going to line number, I am trying to find out a string and then after that, I am adding the value using sed command.
Here is the example
My current file a.yaml
rules:
- name: Block PH by GeoIP country
script: ./rules/Block PH by GeoIP country.js
stage: login_success
enabled: false
........
........
........
- name: Preview-1 API (Test Application)
allowed_clients: []
app_type: non_interactive
callbacks: [] <<<<< ------- see string "callbacks:" with brackets
client_aliases: []
........
........
........
allowed_logout_urls:
- 'http://local.example.com:/login'
allowed_origins: []
callbacks: <<<<< ------- see string "callbacks:" where I want to append
- 'http://local.example.com:/callback'
Command
sed -i "/callbacks:/a \ \ \ \ \ \ - 'https://d1.example.com/callback'" > a.yaml
Results of the Command
My Updated File a.yaml
rules:
- name: Block PH by GeoIP country
script: ./rules/Block PH by GeoIP country.js
stage: login_success
enabled: false
........
........
........
- name: Preview-1 API (Test Application)
allowed_clients: []
app_type: non_interactive
callbacks: []
- 'https://d1.example.com/callback' <<<<< ------- see problem here
client_aliases: []
........
........
........
allowed_logout_urls:
- 'http://local.example.com:/login'
allowed_origins: []
callbacks:
- 'https://d1.example.com/callback' <<<<< ------- I appended
- 'http://local.example.com:/callback'
What I want
rules:
- name: Block PH by GeoIP country
script: ./rules/Block PH by GeoIP country.js
stage: login_success
enabled: false
........
........
........
- name: Preview-1 API (Test Application)
allowed_clients: []
app_type: non_interactive
callbacks: [] <<<<< ------- I don't want to append here
client_aliases: []
........
........
........
allowed_logout_urls:
- 'http://local.example.com:/login'
allowed_origins: []
callbacks:
- 'https://d1.example.com/callback' <<<<< ------- I want my addition only after this
- 'http://local.example.com:/callback'
I don't want to append my line after every matching string, in my above example there are 2 lines having 2 values callbacks: [] and callbacks: so I am trying to append after callbacks: only.
Scenario
I wanted to use sed command in my bash script file where I will pass variable value for this line like this - 'https://$1.example.com/callback' and command would be like this
sed -i "/callbacks:/a \ \ \ \ \ \ - 'https://$1.example.com/callback'" > a.yaml
In this way I can reuse this script by passing any value and append line which will look as below
callbacks:
- 'https://z.example.com/callback'
- 'https://b.example.com/callback'
- 'https://d1.example.com/callback'
- 'http://local.example.com:/callback'