25

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

3 Answers 3

38

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"

0
18

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.

1

In addition to the question you asked, I'll expand on that to give the syntax for the current line number starting at the beginning of the selected block:

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

(first line of the block will be zero)

1
  • I'm not sure if there's an expression which doesn't need to repeat '<, and instead refers directly to the range of the action that is being performed in case you use a different range expression.
    – sh1
    Oct 4, 2023 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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