Home > front end >  Using SED to comment or uncomment a line in YAML
Using SED to comment or uncomment a line in YAML

Time:03-22

I am trying to comment or uncomment a line using Sed in yaml , couldn't find a method using 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]

I tried these commands as I have white space sed -i '/<pattern>/s/^[#[:space:]]/#/g' file to comment out, sed -i '/<pattern>/s/^[#[:space:]]//g' file to uncomment But issue is that they are removing space , which make yaml format truncated. Ex :

        - 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]

I want to comment / uncomment this force-hash line , in such a way that it maintain it yaml properties i.e to be part of files array Expected output

        - 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]

Thanks

I tried these commands as I have white space 
sed -i '/<pattern>/s/^[#[:space:]]*/#/g' file to comment out,
sed -i '/<pattern>/s/^[#[:space:]]*//g' file to uncomment

CodePudding user response:

I am sure there is a way with yq, I just do not have a need to learn it at this time, so here is an option using sed.

$ sed 's/#\(force-hash.*\)/\1/' 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]

CodePudding user response:

I am not sure if I understood the question correctly but if you want to comment and uncomment known text you can do it as:

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

you don't need to address those whitespaces since you need them, just replace the word with #word.

  • if you got what you wanted you can add the -i flag which I removed above for testing.
  • Related