Linux
匹配精確字元串後如何在 Linux yaml 文件中使用 sed 追加一行
我無法找到一種方法在字元串完全匹配後在 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'
您可以使用
$
匹配行尾:sed -i "/callbacks:$/a\ \ - 'https://d1.example.com/callback'" a.yaml