13

I'd like to replace 'x' in this file with current line number. That is, change

x
x
x

to

1
2
3

For now, I use a Perl one-liner:

perl -pi -e '$x=$.; s/x/$x/' myfile.txt

I think UltraEdit can do it with a vertical select and replace. Can this be done in vim? (My example here assumes 'x' is all there is on one line. But the lines in my real file are much more complicated.)

20

Yes, vim can do this! Do a global search for x, and replace it with \=printf("%d", line('.'). For example:

:%s/x/\=printf("%d", line('.'))

You can also change x to another search, if you need to.

Explanation:

This replaces every occurence of x (or whatever you search for) with the evaluation register \=. This register evaluates vimscript code, and returns a string. In this case, the code being evaluated is "Print the line we are on as a decimal number"

9

Since you mentioned vertical select and replace, you can do that too. Use CtrlV to do select the lock of text you want to replace, then c and type 0, to replace that with 0s. Then, select those 0s:

enter image description here

Then press g<c-a> (g+Ctrla):

enter image description here

If you had replaced a single column, then you can use gv to quickly reselect the same area.

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.