alec
alec

Reputation: 395

search and replace through multiple ranges in vim

I'm trying to search/replace through one range of lines and through a second range of lines, via a single command.

Find and replace strings in vim on multiple lines says I should be able to do it like this:

:2,10s/\n/ /g | 12,18&&

but that just gives me: 9 substitutions on 1 line for the first range (as expected), and E16: Invalid range for the second.

Why doesn't the second range work?

I've also tried the command like:

:2,10s/\n/ /g | :12,18&&

with the same result.

Upvotes: 0

Views: 1531

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172590

Reversing the ranges is helpful here, another approach would be to set marks for the subsequent ranges. Vim automatically adapts those for additions / deletions:

:12mark a | 18mark b | 2,10s/\n/ /g | 'a,'b&&

In general, it's best to avoid such sequences; often, a single :global command can do the iteration for you (and this also has automatic line adaptation).

Upvotes: 2

alec
alec

Reputation: 395

Haha... ok, replacing linebreaks with spaces in the first range causes my second range to not exist, as lines 12-18 change to something like 3-9. Solution is to flip the ranges so the range later in the file comes first in the command:

:12,18s/\n/ /g | 2,10&&

Upvotes: 2

Related Questions