Search code examples
commentsjqyq

How to prevent yq removing comments and empty lines?


Here Edit yaml objects in array with yq. Speed up Terminalizer's terminal cast (record) I asked about how to edit yaml with yq. I received the best answer. But by default yq removes comments and empty lines. How to prevent this behavior?

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

execute

yq -y . input.yml

result

command: fish -l
cwd: null
env:
  recording: true
cols: 110

Solution

  • In some limited cases you could use diff/patch along with yq.
    For example if input.yml contains your input text, the commands

    $ 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
    

    creates a file input.yml.new with comments preserved but recording changed to 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