0

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.

Community
  • 1
  • 1
alec
  • 345
  • 3
  • 14
  • [https://stackoverflow.com/questions/19994922/find-and-replace-strings-in-vim-on-multiple-lines](https://stackoverflow.com/questions/19994922/find-and-replace-strings-in-vim-on-multiple-lines) I believe you will find the answer in here. – XIAOHAN SHEN Feb 05 '20 at 19:58

2 Answers2

2

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&&

alec
  • 345
  • 3
  • 14
2

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

Ingo Karkat
  • 167,457
  • 16
  • 250
  • 324