0

I am having a very long line file, I have to break the line into number of small lines.

Example:

< this>is a testing< /this>< next>testing< /next>< tested>successfully< /tested>

I have to break it into as of below

< this>is a testing< / this> 

< next>testing< / next> 

< tested>successfully< /tested>

for this I am trying to search for < and add new line, but this results in:

< this>is a testing

< /this>

< next>testing

< /next>

< tested>successfully

< /tested>

What would be the correct command to fix this?

  • 1
    What you are looking for is not a simple search and replace it is a way to format some html or xml which is much more complex and has much more edge cases than you might think. To do this I would recommend using a specialized tool (there are plenty like this or this) it will be much easier and more efficient than crafting your own regex. And you can even use equalprg to use these tools directly within vim (see :h 'equalprg') – statox Aug 14 '18 at 8:15
  • Not exactly what you are looking for, but I prefer this: %s#<\(/\w\+>\|\w\+/>\)\zs#\r#g, which will add a linebreak after each closing tag. – Christian Brabandt Aug 15 '18 at 5:52
  • Check this out vim.wikia.com/wiki/Cleanup_your_HTML – Alex Kroll Sep 13 '18 at 15:35
1

If for some reason you can't check those tools that statox recommended, you can use something like this:

%s;\(< */[^>]\+>\);\1^M;g

It will look at every line for every closing tag (\(< */[^>]\+>\)) and replace it by itself and then a new line.

The first part (to identify the closing tag) will search for

  • a < character
  • followed by any number of spaces ( *),
  • then a slash (/)
  • and any (positive) number of any character different from a closing tag sign ([^>]\+)
  • and finally a close tag sign (>).

To insert a new line (^M above) you should press Ctrl-V (or Ctrl-Q if you are on on Windows) and then press the Enter key.

  • 1
    This can be simplified to :%s;< */[^>]\+>;&\r;g – do you have very magic set as default? With the default magic setting, (, ) and + need to be escaped, see :h magic. – dessert Dec 13 '18 at 20:40
0

What you need to find all >< patterns and to insert two new lines.

One of the simplest is to do

:s/></>\r\r</g

Or

:s/>\zs\ze</\r\r/g
  • But what if there’s an empty one like < that>< / that>? – dessert Dec 13 '18 at 20:43
  • 1
    Ha, I only considered the case in the OP. – Liu Sha Dec 14 '18 at 1:19

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.