如何在匹配精确字符串后使用 sed 在 Linux yaml 文件中追加一行

如何在匹配精确字符串后使用 sed 在 Linux yaml 文件中追加一行

我无法找到一种方法在字符串精确匹配后在 yaml 文件中追加一行,但忽略一行中具有其他值的类似字符串。有一些例子,但那不是我的情况。我有一个 yaml 文件,我正在自动化其配置,而不是通过转到行号手动添加值,我试图找出一个字符串,然后使用 sed 命令添加值。

这是例子

我当前的文件 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'

命令

sed -i "/callbacks:/a \ \ \ \ \ \ - 'https://d1.example.com/callback'" > a.yaml

命令的结果

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'

我想要的是

    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'

我不想在每个匹配的字符串之后附加我的行,在上面的示例中,有 2 行有 2 个值回调:[] 和回调:所以我尝试仅在回调:之后附加。

设想

我想在 bash 脚本文件中使用 sed 命令,我将像这样传递此行的变量值 - 'https://$1.example.com/callback' 并且命令如下

sed -i "/callbacks:/a \ \ \ \ \ \ - 'https://$1.example.com/callback'" > a.yaml

通过这种方式,我可以通过传递任何值并附加行来重用该脚本,如下所示

  callbacks:               
    - 'https://z.example.com/callback'
    - 'https://b.example.com/callback'
    - 'https://d1.example.com/callback'
    - 'http://local.example.com:/callback'

答案1

您可以使用$来匹配行尾:

sed -i "/callbacks:$/a\
\    - 'https://d1.example.com/callback'" a.yaml

相关内容