Rob Bednark
Rob Bednark

Reputation: 28222

How to run command-line command on non-contiguous lines, specifying individual line numbers?

For example, say I want to replace foo with bar on lines 1,3,11, and 15. How could I do that?

:1,15s/foo/bar

will replace foo with bar on lines 1-15. But I want to specify multiple individual lines (1,3,11,15), not a range (1-15).

Upvotes: 3

Views: 248

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172768

How do you come up with the line numbers? If this is a manual process of visual inspection, you could make use of the multiselect plugin. It allows you to select multiple, non-contiguous ranges, and then you can apply a command on them:

:MSExecCmd s/foo/bar

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172768

One way: Execute the :substitute for the first line, then repeat the same substitution with :&& on the following lines.

:execute '1s/foo/bar' | 5&& | 11&& | 15&&

Another way: Use the :global command with a pattern that matches only in the lines.

:g/\%1l\|\%5l\|\%11l\|\%15l/s/foo/bar

Third way: Use a loop:

:for l in [1,5,11,15] | execute l.'s/foo/bar' | endfor

Upvotes: 6

Related Questions