【问题标题】:Remove a matching string after a specific string a file using shell command使用 shell 命令删除文件中特定字符串后的匹配字符串
【发布时间】:2023-01-24 21:54:45
【问题描述】:

我的文件 abcd.yml 中有以下内容,缩进如下:

buildConfig:
  env:
    credentials:       # want to remove this from file
      - id: TEST_ID    # want to remove this from file
        user: username # want to remove this from file 
        password: password  # want to remove this from file
scan:
    credentials:
      - id: scan_id
        user: username
        password: password 

尝试了以下:

sed -i '/credentials:/d'  abcd.yml
sed -i '/- id: TEST_ID/d'  abcd.yml
sed -i '/user: username/d'  abcd.yml
sed -i '/password: password/d'  abcd.yml

但它正在从我不想要的文件中删除所有出现的上述字符串。

预期输出:

buildConfig:
  env:
scan:
    credentials:
      - id: scan_id
        user: username
        password: password 

需要为 1000 个文件执行此操作。因此需要一个脚本来执行此操作。文件为 .yml 格式。

【问题讨论】:

  • 你用谷歌搜索过 yaml 编辑器吗?我听说 yq 可用于 Unix。

标签: shell unix awk sed grep


【解决方案1】:

为此使用yml parser

$ yq eval 'del(.buildConfig.env.credentials)' abcd.yml > newfile.yml
$ cat newfile.yml

buildConfig:
  env: {}
scan:
  credentials:
    - id: scan_id
      user: username
      password: password

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-03
    • 2017-09-24
    • 2019-11-06
    • 2020-07-11
    • 1970-01-01
    • 2013-08-08
    相关资源
    最近更新 更多