如何防止 yq 删除注释和空行?

kyb*_*kyb 6 comments jq yq

这里使用 yq 编辑数组中的 yaml 对象。加速 Terminalizer 的终端转换(记录)我问过如何用 yq 编辑 yaml。我得到了最好的答案。但默认情况下yq会删除注释和空行。如何防止这种行为?

input.yml

# Specify a command to be executed
# like `/bin/bash -l`, `ls`, or any other commands
# the default is bash for Linux
# or powershell.exe for Windows
command: fish -l

# Specify the current working directory path
# the default is the current working directory path
cwd: null

# Export additional ENV variables
env:
  recording: true

# Explicitly set the number of columns
# or use `auto` to take the current
# number of columns of your shell
cols: 110
Run Code Online (Sandbox Code Playgroud)

执行

yq -y . input.yml
Run Code Online (Sandbox Code Playgroud)

结果

command: fish -l
cwd: null
env:
  recording: true
cols: 110
Run Code Online (Sandbox Code Playgroud)

jq1*_*727 8

在某些有限的情况下,您可以将 diff/patch 与 yq 一起使用。
例如,如果input.yml包含您的输入文本,则命令

$ yq -y . input.yml > input.yml.1
$ yq -y .env.recording=false input.yml > input.yml.2
$ diff input.yml.1 input.yml.2 > input.yml.diff
$ patch -o input.yml.new input.yml < input.yml.diff
Run Code Online (Sandbox Code Playgroud)

创建一个input.yml.new保留注释但记录更改为 false 的文件:

# Specify a command to be executed
# like `/bin/bash -l`, `ls`, or any other commands
# the default is bash for Linux
# or powershell.exe for Windows
command: fish -l

# Specify the current working directory path
# the default is the current working directory path
cwd: null

# Export additional ENV variables
env:
  recording: false

# Explicitly set the number of columns
# or use `auto` to take the current
# number of columns of your shell
cols: 110
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的这个主意。我使用了最近的 `yq` 版本 4.2.0,这是向前迈出的一大步(对于那些使用 `jq` 的人来说也是如此,该版本在保留注释方面没有问题。但是,我在保留空白行方面遇到了问题,我能够使用 diff 的 `-B` 选项来规避。使用一些 bashisms,我可以将其作为单行代码: `diff -B "$src_file" &lt;(yq eval "$eval_line" "$src_file") | patch -o - “$src_file”` (6认同)