3

I've file in which there are some repeated parts and I want to get rid of the first occurrence. Normally I'd do %s/_exclude// to perform substitute for all lines, however I want to replace only the first occurrence in the file, e.g. having:

name = foo
# unknown number of lines ...
features_exclude[rules_config][] = rule1 
features_exclude[rules_config][] = rule2 
features_exclude[rules_config][] = rule3 
features_exclude[rules_config][] = rule4

I'd like to do remove first occurrence of _exclude, so it becomes:

name = foo
# unknown number of lines ...
features[rules_config][] = rule1 
features_exclude[rules_config][] = rule2 
features_exclude[rules_config][] = rule3 
features_exclude[rules_config][] = rule4

So if I repeat the action again, it'll remove the next one (on whichever line it is) and so on.

What's the easiest way of doing that?

  • According to :h :s you can use a count after a substitute command like :%s/_exclude// 1 but for a reason that I don't understand it begins with the last line of the range so it would have an action on rule4. Also you talk about removing the whole line but your substitute command only remove the word _exclude is it what you actually want? Finally wouldn't a search /_exclude followed by normal mode dd wouldn't be what you're looking for? – statox Apr 5 '16 at 10:06
  • Removing only _exclude text, not the line. – kenorb Apr 5 '16 at 10:09
  • you can do a substitution using line number if you know line numbers – Nagaraju Apr 5 '16 at 11:29
  • @Raju I assume I won't be able to know the line numbers. – kenorb Apr 5 '16 at 11:30
  • 2
    stackoverflow.com/a/25840884/1848140 try this – Nagaraju Apr 5 '16 at 11:33
8

Here is the method using pattern matches:

:/_exclude/s/_exclude//

It will first identify the line which has _exclude, then do the substitution on that line (s/_exclude//).

To repeat the last command-line change, use the @: command.


This can be simplified further more as per @muru suggestion by:

:/_exclude/s///

since an empty pattern will use the previous pattern.

  • 4
    You can condense that to :/_exclude/s///. If given an empty pattern, :s will re-use the previous pattern, which, in this case would be _exclude from :/. – muru Apr 5 '16 at 10:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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