Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VI Regular Expressions - Replacing using current line number

Tags:

regex

vim

I'm not sure it's possible or not, but one of the things I find I need to do often is to replace the contents of the file, but I want to use the current line number as a replacement option. So if I had a file like:

This is text to replace XX 
This is text to replace XX 
This is text to replace XX

I would want to be able to run a regex that would turn that file into:

This is text to replace 1
This is text to replace 2
This is text to replace 3

I've looked around, but I can't seem to find any way of doing this. Is this possible? Does anyone know of a simple way to approach this?

Thanks.

like image 509
Ryan Smith Avatar asked Mar 09 '09 20:03

Ryan Smith


People also ask

How do you substitute in vi?

Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .

Can you replace with regex?

replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

:help sub-replace-expression

You can construct a replace expression like:

:s@ xx$@\=" " . line(".")@

... Which works for me.

like image 182
greyfade Avatar answered Oct 16 '22 21:10

greyfade