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




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.)


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.


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"

  • Thank you Sir! That works as expected. (Is there a way to vote for an answer? Or something like Facebook "Like"?) – yong321 Jun 10 '16 at 21:51
  • @yong321 Glad to hear it helped you! There are two options for voting for an answer: 1. voting for an answer, which you will be able to do when you have 15 reputation and 2. accepting an answer (clicking the green checkmark). You can read more about both of those here – DJMcMayhem Jun 10 '16 at 21:56

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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