Text-Processing

在不使用外部工具的情況下解析 yaml 文件

  • February 12, 2021

我是 bash 新手,遇到了需要更新 yaml 文件中的一些動態參數的問題

基於查詢(search4.subsearch1.name),我需要更新

name: old_name

進入

name: new_name
  • 這是範例文件:
search1:
   name: name1
   pass: pass1
   date: date1
#these are just commented texts

search2:
 #Adding few more commented lines
   myname: somename
   name: name2
   pass: pass2
   someotherparam: param1

search3:
   nameAndSurname: NS
   namingConv: true
   varSet: P3

search4:
   #Again adding some special name: strings here
       myname: somename1
       name: new_name
       pass: new_pass
       ptherparam1: T3

   subsearch1:
       #Again adding some special name strings here
           myname: somename2
           name: old_name
           pass: pass2
           ptherparam1: param3
search5:
   #Again adding some special name strings here
       var1: value1
       name: some_name
       pass: some_pass

所以基於查詢(search4.subsearch1.name),我需要更新name: old_namename: new_name

  • 預期輸出:
search4:
   #Again adding some special name: strings here
       myname: somename1
       name: new_name
       pass: new_pass
       ptherparam1: T3

   subsearch1:
       #Again adding some special name strings here
           myname: somename2
           name: new_name
           pass: pass2
           ptherparam1: param3

嘗試過awksed但沒有奏效:

lineNR=$(awk "/\<search4:/{f=1} f && /\<name:/ {print NR; exit}" testfile.txt);sed "${lineNR}s/name.*/name: new_name/" testfile.txt

您還沒有告訴我們您正在使用什麼系統或已經安裝了什麼系統。所以這只是一個有根據的猜測。許多 linux 發行版都帶有“python”,而 yaml 的興起意味著庫“pyaml”也經常被安裝。您自己與 yaml 文件互動的事實使這種情況更有可能發生。

你可以很容易地測試它。製作一個foo.py僅包含以下內容的文件:

import yaml
print("I have yaml")

然後在命令行執行:

python3 foo.py

如果它只是列印I have yaml,那麼你已經安裝了 python 和 pyaml,並且可以在一個簡單的腳本中使用它(update_script.py):

import yaml
import sys

# Load the file into a data structure
with open(sys.argv[1], "r") as file:
   content = yaml.safe_load(file)

# Update the key you want to change
content["search4"]["subsearch1"]["name"] = "new_name"

# Write the data structure back to your file in YAML
with open(sys.argv[1], "w") as file:
   yaml.safe_dump(content, file)

然後執行:

python3 update_script.py config_file.yaml

假設您可以下載並安裝Mike Farahyq,則該過程變得微不足道

yq eval '.search4.subsearch1.name = "new_name"' file.yml

我注意到您在評論中說“我們沒有網際網路連接,並且這些 linux 盒子中不允許使用任何外部軟體包”。即使您自己不允許添加軟體包,也會有一個管理流程來要求將軟體添加到這些系統中。也許是“更改請求”。有時值得經歷明顯的痛苦來傳遞更可靠的軟體,而這些軟體反過來更容易支持


為了測試,我必須編輯內容以確保縮進在search4. 我沒有編輯問題本身的內容

引用自:https://unix.stackexchange.com/questions/633696