Insert a line of text before lines matching a regex in vim

2

I'm attempting to add a column to an HTML table using vim so I need to add a pair of <td> tags the line before each </tr>. So far I have

:186,$s/ <\/tr>/<td><\/td> \n <\/tr>/g
but vim shows ^@ instead of making a new line for the closing tr tag. Is there any way around that?

Yitzchak

Posted 2014-07-10T15:14:51.483

Reputation: 4 084

Answers

4

Yes, you need to use \r instead of \n in the replacement part, a quirk of Vim's :s command. And you can further simplify the command by using a different separator, e.g. #, and by referring to the match via &:

:186,$s# </tr>#<td></td> \r&#g

Ingo Karkat

Posted 2014-07-10T15:14:51.483

Reputation: 19 513

Thanks! I'm a little confused because I thought that \n was the linux newline character and \r\n was for windows. Also, what does it mean to "refer to the match with &? – Yitzchak – 2014-07-10T15:25:17.850

1That's explained at :h s/\r and :h s/\&, resp. The & contains the match, i.e. </tr>, so you don't need to repeat it. You could also use an assertion with \zs, but that's even more advanced... – Ingo Karkat – 2014-07-10T15:28:41.760