2

I have the following text in File.XML:

<http-listener name="default" socket-binding="http" max-post-size="1073741824" />

I would like to replace that with

<!-- <http-listener name="default" socket-binding="http" max-post-size="1073741824" /> -->>

I tried

sed -i 's/<http-listener name="default" socket-binding="http" max-post-size="1073741824" /><!-- <http-listener name="default" socket-binding="http" max-post-size="1073741824" /> -->>' test.xml

But got error

2

Insert the required chunk (<!--) at start (^):

sed 's/^/<!-- /'

Example:

% var='<http-listener name="default" socket-binding="http" max-post-size="1073741824" />'

% sed 's/^/<!-- /' <<<"$var"
<!-- <http-listener name="default" socket-binding="http" max-post-size="1073741824" />

Just to note, to parse structured data like xml, you should use a tool that understands the structure e.g. xmlstarlet.


Answer to the edited question:

You can match precise substring at start and end, in the replacement use \0 to refer the whole match putting desired replacement substrings around:

sed 's/^<http-listener name="default".*>$/<!-- \0 -->>/'

Example:

% var='<http-listener name="default" socket-binding="http" max-post-size="1073741824" />'

% sed 's/^<http-listener name="default".*>$/<!-- \0 -->>/' <<<"$var"                     
<!-- <http-listener name="default" socket-binding="http" max-post-size="1073741824" /> -->>
  • 1
    No need for extended regex, you can save -E. In the command OP tried there’s an additional ` -->>` at the end of the line, so maybe OP wants sed 's_<http… />_<!-- & -->>_ – with a different delimiter because the original line contains a slash. – dessert Aug 1 '18 at 18:52
  • sed -i 's_<http-listener name="default" socket-binding="http" max-post-size="1073741824" />_<!-- & -->_' test.xml @dessert. It works fine. Nice info – Picasu27 Aug 2 '18 at 6:24
  • 1
    @dessert Nice emoji in there :) – Sergiy Kolodyazhnyy Aug 2 '18 at 6:39
  • @dessert -E has become sort of a muscle memory...hahaha.... – heemayl Aug 2 '18 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.