使用 SED 注释或取消注释 YAML 中的行

Using SED to comment or uncomment a line in YAML

我试图在 yaml 中使用 Sed 注释或取消注释一行,找不到使用 yq 的方法。

        - files:
            force-magic: no   # force logging magic on all logged files
            # force logging of checksums, available hash functions are md5,
            # sha1 and sha256
            #force-hash: [md5]

我尝试了这些命令,因为我有白色 space sed -i '//s/^[#[:space:]]/#/g' 文件注释掉, sed -i '//s/^[#[:space:]]//g' 文件取消注释 但问题是他们正在删除 space ,这使得 yaml 格式被截断。 例如:

        - files:
            force-magic: no   # force logging magic on all logged files
            # force logging of checksums, available hash functions are md5,
            # sha1 and sha256
force-hash: [md5]

我想评论/取消评论此强制哈希行,以维护它的 yaml 属性的方式,即成为文件数组的一部分 预期输出

        - files:
            force-magic: no   # force logging magic on all logged files
            # force logging of checksums, available hash functions are md5,
            # sha1 and sha256
            force-hash: [md5]
Solution
sed 's/force-hash/\# force-hash/g' <name_of_file> #this will comment your line   
sed 's/#\(force-hash.*\)//' <name_of_file> #to uncomment

我不确定我是否正确理解了这个问题,但如果您想评论和取消评论已知文本,您可以这样做:

sed 's/force-hash/\# force-hash/g' <name_of_file> #this will comment your line
sed 's/# force-hash/\force-hash/g' <name_of_file> #this will uncomment your line

您不需要解决这些空格,因为您需要它们,只需将单词替换为#word。

  • 如果你得到了你想要的,你可以添加我在上面删除的 -i 标志以进行测试。

我相信 yq 是有办法的,我只是暂时没有必要学习它,所以这里有一个使用 sed.

的选项
$ sed 's/#\(force-hash.*\)//' input_file
 - files:
            force-magic: no   # force logging magic on all logged files
            # force logging of checksums, available hash functions are md5,
            # sha1 and sha256
            force-hash: [md5]