Skip to content
Advertisement

Unix – Uncomment xml comments

I have below node from XML file. How do I uncomment the first occurrance of mainHost using Unix shell script or commands?

        <!-- Host without authentication -->
            <!-- <mainHost> <hostName>test.com</hostName> <httpPort>80</httpPort>
                    </mainHost> -->
            <!-- Host with authentication userId: User name of Host server Password:
                     -->
            <!-- <mainHost> <hostName>127.0.0.1</hostName> <httpPort>80</httpPort>
                    <userId>username</userId> <password>password</password>
                    </mainHost> -->

I have tried with below command with different variations but that does not seem to work.

sed ‘0,/<!– /{s/<!– //}’ /test.xml

I am expecting below output

        <!-- Host without authentication -->
             <mainHost> <hostName>test.com</hostName> <httpPort>80</httpPort>
                    </mainHost> 
            <!-- Host with authentication userId: User name of Host server Password:
                     -->
            <!-- <mainHost> <hostName>127.0.0.1</hostName> <httpPort>80</httpPort>
                    <userId>username</userId> <password>password</password>
                    </mainHost> -->

Thanks

Advertisement

Answer

You were on the right track (under the assumption that sed has to be used).

Create a file (for example script.sed) with the following content:

0,/</mainHost>/{
  /<mainHost>/,/</mainHost>/{
    s/<!--//
    s/-->//
  }
}

and run sed -f script.sed FILE.xml.

Note that this solution is difficult to generalize. sed may not be the best tool for the task.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement