1

Is there any option to replace the first occurrence without asking for confirmation in vim?

I want to replace New York with \place{New York} in the first occurrence only without asking for confirmation. I used this code:

silent! /\\begin{text}/,/\\end{textit}/s/New York/\\place{New York}/g

> \begin{text}..[paragraphs]...\end{textit}

New York may be contained 10 times in the paragraph.

Régis B.
  • 10,092
  • 6
  • 54
  • 90
Zam
  • 367
  • 2
  • 17

2 Answers2

3

So you want to in a line range do only single substitution, not one sub per line. So the /start/,/end/ s/pat/rep/ will not work. I would make your example simpler, given that we have:

foo
nyc nyc
nyc nyc
bar

I guess what you are expecting to have is

foo
\\place{nyc} nyc
nyc nyc
bar

However :/foo/,/bar/ s/nyc/\\place{&} will give

foo
\\place{nyc} nyc
\\place{nyc} nyc
bar

Because :s will do sub for each line in range.

I would narrow the range to solve this problem:

/foo//nyc/s/nyc/\\place{&}/

note that between /foo/ and /nyc/, there is no comma.

The output should be:

foo
\\place{nyc} nyc
nyc nyc
bar

You may want to read :h range for details.

Kent
  • 189,393
  • 32
  • 233
  • 301
2

The /g flag at the end of your substitution means that it will be performed on every occurence of your search pattern. Remove it and it will only be performed on the first occurence.

Also, :s doesn't ask for confirmation by default; you would need to add the /c flag for that. So I'm not sure why you prepend it with :silent.

Another comment: You can reuse the matched text in the replace part with &:

:/\\begin{text}/,/\\end{textit}/s/New York/\\place{&}
romainl
  • 186,200
  • 21
  • 280
  • 313
  • if a pattern is not found then, it show some error msg ,like pattern not found, if we use silent!, then it will not show the err msgs. – Zam Jan 19 '16 at 10:01
  • Those messages are useful. – romainl Jan 19 '16 at 10:49
  • but i have lot of search patterns in my function, may be 300. so the message shown each time, will made me disturbed. – Zam Jan 21 '16 at 04:11